Objective C iPhone 开发,保存和检索 NSMutableArray
我是 iPhone 开发新手,我正在使用 XCode 4.2 我正在尝试保存 NSMutable 数组,以便当我关闭应用程序并重新打开它时,数据仍然存在 我正在使用这两个函数:
-(void)saveData{
[NSKeyedArchiver archiveRootObject:[data copy] toFile:[self dataFilePath]];
}
- (void)loadData
{
data = [NSKeyedUnarchiver unarchiveObjectWithFile:self.dataFilePath];
}
但我发现两个主要问题: 1-当我切换视图并返回时,数据消失了 2-当我完全退出应用程序时(即双击主按钮并将其从正在运行的应用程序列表中删除),数据也不会被删除,
我发现我可以使用这两个 NSMutableArray 方法:writeToFile< /code> 和
initWithContentsOfFile
但我不知道在哪里调用它们(是当我向 UITableView 添加项目时吗?在 viewDidLoad
中?
有人能给我一个示例吗? ?
提前感谢
I am new to iPhone development and I am using XCode 4.2
I am trying to save an NSMutable array so that when I close the application and reopen it , the data will still be there
I am using these two functions :
-(void)saveData{
[NSKeyedArchiver archiveRootObject:[data copy] toFile:[self dataFilePath]];
}
- (void)loadData
{
data = [NSKeyedUnarchiver unarchiveObjectWithFile:self.dataFilePath];
}
but I found two major issues :
1- when I switch views and come back , the data is gone
2- when I completely exit the application (i.e. I double click on the Main button and remove it from the list of running application) the data is not erased as well
I found that I can use these two NSMutableArray methods : writeToFile
and initWithContentsOfFile
but I don t know where to call them (is it when I add items to the UITableView ? in the viewDidLoad
?
can somebody give me a sample code?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要保存数组,请使用 writeToFile:atomically: 方法。它将把您的
NSArray
内容保存为 plist 文件。要从 plist 文件加载数组,请使用 initWithContentsOfFile: 方法。请注意,只有当您的数组具有以下类实例
NSString
、NSData
、NSDate
时,这些方法才能够保存您的内容,NSNumber
NSArray
或NSDictionary
作为项目。您可以调用保存/加载方法,如下所示
For saving an array use
writeToFile:atomically:
method. It will save yourNSArray
content as plist file. For load an array from plist file, useinitWithContentsOfFile:
method.Please note, that these methods will be able to save your stuff, only if your array has the following class instances
NSString
,NSData
,NSDate
,NSNumber
NSArray
, orNSDictionary
as items.you can call save/load methods like following
问题是,当这两个操作发生时,saveData 不会被调用。因此,我建议在这个方法的 AppDelegate 上保存数据来解决问题 2(退出应用程序)
至于问题 1(切换视图时),您只需要在 viewController 上的这个方法上调用 saveData:
希望有帮助。
The problem is that when those 2 actions happen, saveData is not getting called. Therefore I would suggest saving your data on the AppDelegate on this method to solve problem 2 (exit app)
As for problem 1 (when switching views), you just need to call your saveData on this method on your viewController:
Hope that helps.