Ios string=textView.text,但字符串为(nul)

Ios string=textView.text,但字符串为(nul),ios,objective-c,nsstring,uitextview,writetofile,Ios,Objective C,Nsstring,Uitextview,Writetofile,我什么都试过了。我肯定我的错误会像错过的self.string一样愚蠢和渺小,但我似乎无法让它发挥作用。我的小程序所做的是检查名为Code.txt的文件是否已经存在。如果它确实存在,那么它将在UITextView中加载该文件(而且它做得很好)。如果它不存在,它将创建一个文件名Code.txt。所有这些都很好 但是,当我试图将UITextView中的当前文本保存到文件中时,无法先将其保存到字符串中。这就是我努力实现的目标: 退出应用程序时:textView.text-->代码字符串-->code.

我什么都试过了。我肯定我的错误会像错过的self.string一样愚蠢和渺小,但我似乎无法让它发挥作用。我的小程序所做的是检查名为Code.txt的文件是否已经存在。如果它确实存在,那么它将在UITextView中加载该文件(而且它做得很好)。如果它不存在,它将创建一个文件名Code.txt。所有这些都很好

但是,当我试图将UITextView中的当前文本保存到文件中时,无法先将其保存到字符串中。这就是我努力实现的目标:

退出应用程序时:
textView.text-->代码字符串-->code.txt[已保存]

除此之外,我无法将textView.text保存到字符串(
code字符串
)。NSLog将其作为螺母返回(请参见saveFile方法中的
NSLog(@“String:%@”,self.codeString);

ViewController.h

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "BuildViewController.h"

@interface ViewController : UIViewController <UITextViewDelegate>

@property (nonatomic, strong) NSString *codeString;
@property (nonatomic, retain) IBOutlet UITextView *textView;
@property (nonatomic, retain) BuildViewController *buildViewController;

- (void)saveFile;

@end

您的错误是创建了一个新的
ViewController
实例,如@Avi所说

您应该在内存中获取现有实例

若要在后台保存文件,可以注册通知

viewDidLoad
中,添加此行

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
然后将此功能添加到
ViewController

-(void)enterBackground:(NSNotification *)notification{
    [self saveFile];
}
然后在Dealoc

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}

saveFile在哪里调用?@JörnBuitink很抱歉,正在从AppDelegate的ApplicationIdentinterBackground调用saveFile,并且应用程序将终止:
ViewController*ViewController=[ViewController alloc];[视图控制器保存文件]
您是否真的在
ApplicationIdentinterBackground
中创建了视图控制器的新实例?@MattSwift在这种情况下,textview将不再存在,您调用函数太晚了。例如,尝试调用您的函数来调用ViewControllers ViewWillEnglishe。@JörnBuitink@Avi似乎当我将它添加到
ViewWillEnglish
中时,它确实有效。但是,只有在我即将终止应用程序时,而不是在我将其置于后台时。我的应用程序现在崩溃:
[UINavigationController saveFile]:发送到实例0x15c815600 2015-12-08 03:03:21.879 app[3485:917222]***由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:-[UINavigationController saveFile]:无法识别的选择器发送到实例0x15c815600'
尝试更新方式,您可以在进入后台时注册通知。
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}