将 NSMutableArray 保存到 plist 中?

发布于 2024-11-19 00:21:32 字数 575 浏览 1 评论 0原文

可能的重复:
iOS:在 .plist 文件中存储两个 NSMutableArray

iOS:在 我正在开发的应用程序有一堆“注册”对象,其中包含一些字符串、日期和整数。 所有这些对象在创建时都存储在 NSMutableArray 中,我现在想以某种方式保存该数组,以便当用户关闭应用程序等时,可以存储内容并在应用程序再次打开时恢复内容。

我读过 plist 可能是最好的方法,但我似乎找不到任何示例、帖子等来说明如何做到这一点?

所以基本上:当应用程序关闭时,如何将 NSMutableArray 保存到 plist 文件,以及如何再次恢复它?

Possible Duplicate:
iOS: store two NSMutableArray in a .plist file

In the app I'm working on I have a bunch of "Registration" objects that contain some strings,dates and integers.
All of these objects are stored in a NSMutableArray when they're created, and I now want to save this array in someway, so that when the user closes the app etc., the content can be stored and restored when app opens again.

I've read that plist is probably the best way to do so, but I can't seem to find any examples, posts etc. that show how to do it?

So basicly: How to I save my NSMutableArray to a plist file when app closes, and how to restore it again?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寂寞清仓 2024-11-26 00:21:32

NSMutableArray 有一个方法可以做到这一点,如果你确切知道将其保存到哪里:

//Writing to file
if(![array writeToFile:path atomically:NO]) {
    NSLog(@"Array wasn't saved properly");
};

//Reading from File
NSArray *array;
array = [NSArray arrayWithContentsOfFile:path];
if(!array) {
    array = [[NSMutableArray alloc] init];
} else {
    array = [[NSMutableArray alloc] initWithArray:array];
};

或者你可以使用 NSUserDefaults:

//Saving it
[[NSUserDefaults standardUserDefaults] setObject:array forKey:@"My Key"];

//Loading it
NSArray *array;
array = [[NSUserDefaults standardUserDefaults] objectForKey:@"My Key"];
if(!array) {
    array = [[NSMutableArray alloc] init];
} else {
    array = [[NSMutableArray alloc] initWithArray:array];
};

NSMutableArray has a method for doing this, if you know exactly where to save it to:

//Writing to file
if(![array writeToFile:path atomically:NO]) {
    NSLog(@"Array wasn't saved properly");
};

//Reading from File
NSArray *array;
array = [NSArray arrayWithContentsOfFile:path];
if(!array) {
    array = [[NSMutableArray alloc] init];
} else {
    array = [[NSMutableArray alloc] initWithArray:array];
};

Or you can use NSUserDefaults:

//Saving it
[[NSUserDefaults standardUserDefaults] setObject:array forKey:@"My Key"];

//Loading it
NSArray *array;
array = [[NSUserDefaults standardUserDefaults] objectForKey:@"My Key"];
if(!array) {
    array = [[NSMutableArray alloc] init];
} else {
    array = [[NSMutableArray alloc] initWithArray:array];
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文