【问题标题】:string = textView.text, yet string is (nul)string = textView.text,但 string 为 (null)
【发布时间】:2016-03-13 01:19:43
【问题描述】:

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

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

退出应用后:textView.text --> codeString --> Code.txt [saved]

除此之外,我无法将 textView.text 保存到字符串 (codeString)。 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.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize textView;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    textView.delegate = self;

    // Check if Code.txt exists
    NSString* documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *codeFile = [NSString stringWithFormat:@"%@/Code.txt", documentsDir];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:codeFile];

    NSLog(@"viewWillAppear");

    if (fileExists == true) {
        // Code.txt does exist, continue to viewDidLoad
        NSLog(@"Code.txt does exist");
    }

    else if (fileExists == false) {
        // Code.txt does not exist, create the file
        NSLog(@"Code.txt does not exist");
        ViewController *viewController = [ViewController alloc];
        [viewController createFile];
    }

    self.textView.delegate = self;
}

- (void)viewWillAppear:(BOOL)animated {
    // Load Code.txt
    NSString* documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* codeFile = [documentsDir stringByAppendingPathComponent:@"Code.txt"];
    NSString *codeString = [NSString stringWithContentsOfFile:codeFile encoding:NSUTF8StringEncoding error:NULL];
    textView.text = codeString;
    NSLog(@"Loaded Code.txt");
}

- (void)saveFile {
    // Save text to Code.txt
    self.codeString = textView.text;
    NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *codeFile = [NSString stringWithFormat:@"%@/Code.txt", documentsDir];
    [self.codeString writeToFile:codeFile
                 atomically:NO
                   encoding:NSStringEncodingConversionAllowLossy
                      error:nil];
    NSLog(@"String: %@", self.codeString);
    NSLog(@"Saved text to Code.txt");
}

- (void)createFile {
    NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *codeFile = [NSString stringWithFormat:@"%@/Code.txt", documentsDir];
    NSString *codeString = @"print(\"Hello, world\")";
    [codeString writeToFile:codeFile
              atomically:NO
                encoding:NSStringEncodingConversionAllowLossy
                   error:nil];
    NSLog(@"Created Code.txt");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

【问题讨论】:

  • saveFile 在哪里调用?
  • @JörnBuitink 抱歉,正在从 AppDelegate 的 applicationDidEnterBackground 和 applicationWillTerminate 调用 saveFile:ViewController *viewController = [ViewController alloc]; [viewController saveFile];
  • 您是否真的在applicationDidEnterBackground 中创建了视图控制器的新实例?
  • @MattSwift 在这种情况下,文本视图将不再存在,您调用函数为时已晚。例如,尝试 ViewControllers viewWillDisappear 来调用您的函数。
  • @JörnBuitink @Avi 似乎当我将它添加到viewWillDisappear 时,它确实有效。但是,仅在我即将终止应用程序时,而不是在我将其置于后台时。

标签: ios objective-c nsstring uitextview writetofile


【解决方案1】:

您的错误是您像@Avi 所说的那样创建了ViewController 的新实例。

你应该得到内存中的现有实例

如果你想在后台保存文件,你可以注册通知

viewDidLoad,添加这一行

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];

然后将此函数添加到ViewController

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

然后在dealloc中

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

【讨论】:

  • 我的应用程序现在崩溃了:[UINavigationController saveFile]: unrecognized selector sent to instance 0x15c815600 2015-12-08 03:03:21.879 App[3485:917222] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UINavigationController saveFile]: unrecognized selector sent to instance 0x15c815600'
  • 试试更新方式,进入后台可以注册通知。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
  • 2019-06-24
  • 1970-01-01
相关资源
最近更新 更多