ios - 在 iOS5 问题中保存数据

标签 ios xcode ios5 save plist

我正在尝试使用 Beginning iPhone Development 中的这段代码在我的应用程序中保存简单的文本数据:

- (NSString *)dataFilePath { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingFormat:kFileName];
}

- (void)applicationWillTerminate:(NSNotification *)notification { 
    NSMutableArray *array = [[NSMutableArray alloc] init]; 
    [array addObject:field1.text]; 
    [array addObject:field2.text]; 
    [array addObject:field3.text]; 
    [array addObject:field4.text];

    [array writeToFile:[self dataFilePath] atomically:YES];
}

- (void)viewDidLoad { NSString *filePath = [self dataFilePath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
        field1.text = [array objectAtIndex:0];
        field2.text = [array objectAtIndex:1];
        field3.text = [array objectAtIndex:2];
        field4.text = [array objectAtIndex:4];
    }

    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(applicationWillTerminate:)
                                             name:UIApplicationWillTerminateNotification
                                           object:app];

    [super viewDidLoad];
}

此代码是为 iOS 3 编写的,适用于 iOS 5,但不适用于 iOS 5。如果您只需点击模拟器中的主页按钮将其关闭,然后调出多任务栏并点击应用程序图标,数据就会重新加载正好。但是,当您通过点击主页按钮关闭它,然后调出多任务栏并将其也关闭,然后重新启动该应用程序时,数据就消失了。当您从多任务栏关闭应用程序时,我认为该应用程序不会收到它正在终止的通知,但我不确定我是否仍是初学者。

我确信我只需要在已有的代码中添加一行或两行。有谁知道那可能是什么?

最佳答案

我可以建议使用 NSUserDefaults 类吗?它非常适合存储像这样的简单数据。

设置一个值

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"value" forKey:@"field"];
[defaults synchronize];

获取一个值

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSString * value = [defaults objectForKey:@"field"]

关于ios - 在 iOS5 问题中保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8733854/

相关文章:

ios - 不同语言的 iPad 应用程序

ios - "shake is not supported on real devices"错误消息

ios - App 多次被 Apple 拒绝

objective-c - 尝试 segue 时旋转中断

iphone - 现在开始构建 iOS 应用程序并在 1-2 个月内发布时使用哪个 iOS 版本?

ios - 迭代字典数组的数组

ios - 如何在按下按钮时遍历数组中的项目?

ios - iPhone 应用签名 : A valid signing identity matching this profile could not be found in your keychain

xcode - 在 for 循环内附加图像数组 - swift

ios - 在过渡到 iOS 6 期间提交 iOS 5 应用程序