gpt4 book ai didi

ios - 读写 plist(iPhone 编程)

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:21:11 24 4
gpt4 key购买 nike

我正在尝试实现“开始 iPhone 3 开发”一书中的一个简单的 plist 示例。我查看了代码,但我的数据从未保存到 plist 文件中。实际上我的项目站点地图如下:每当您启动应用程序时,它都会在 TestViewController 中触发。在 TestViewController 上,有一个按钮。当您单击按钮时,它会推送另一个 View Controller ,即 PersistenceViewController,这是我在 PersistenceViewController 中编写的代码。我的疑问:是否在此方法中调用了 applicationWillTerminate?我不这么认为..请帮忙。我现在正在学习如何持久化数据。

In .h file #define kFilename @"data2.plist"

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

- (void)applicationWillTerminate:(NSNotification *)notification {
NSMutableArray *contactFormArray = [[NSMutableArray alloc] init];
NSLog(@"App Terminate:%d",[contactFormArray count]);
[contactFormArray addObject:nameField.text];
[contactFormArray addObject:emailField.text];
[contactFormArray addObject:phoneField.text];
[contactFormArray addObject:companyField.text];
[contactFormArray writeToFile:[self dataFilePath] atomically:YES];
[contactFormArray release];
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *contactFormArray = [[NSArray alloc] initWithContentsOfFile:filePath];
NSLog(@"Did Load:%d",[contactFormArray count]);
nameField.text = [contactFormArray objectAtIndex:0];
emailField.text = [contactFormArray objectAtIndex:1];
phoneField.text = [contactFormArray objectAtIndex:2];
companyField.text = [contactFormArray objectAtIndex:3];
[contactFormArray release];
}

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

}

感谢任何宝贵的建议...

最佳答案

applicationWillTerminate 在用户退出应用程序时调用(通常是通过按主页按钮)。此委托(delegate)方法中的任何代码都将被执行(如果不会花费太多时间)。在您的情况下,将保存 Plist 文件。

如果您使用的是 iOS 4,按下主页按钮可能会将您的应用程序发送到后台(而不是退出)。如果应用程序被调试器杀死或崩溃,则不会调用该方法。

附加信息:

在 iOS 4 上,Xcode 项目默认启用多任务处理。这会阻止调用 applicationWillTerminate 方法。如果您不想支持多任务处理,请将 UIApplicationExitsOnSuspend 放在您的 MyAppName-Info.plist 文件中并选中该复选框。如果您确实想要支持它,请将任何代码放入您希望在应用程序进入非事件状态之前执行的 applicationDidEnterBackground 委托(delegate)方法中。

关于ios - 读写 plist(iPhone 编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4209194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com