如何将NSMutableArray保存到本地存储

时间:2014-04-14 15:12:33

标签: ios nsmutablearray

我想将NSMutableArray保存到文件中,并在每次程序运行时加载它。对此最好的解决方案是什么?

这是我的例子:

// I add a new item to ARRAYLIST
NSString *textNewCategory = [alert textFieldAtIndex:0].text;
[ARRAYLIST insertObject:textNewCategory atIndex:0];

// I save ARRAYLIST
userCategory = [NSUserDefaults standardUserDefaults];
[userCategory setObject:ARRAYLIST forKey:@"newCategory"];
NSLog(@"ARRAYLIST 1:%d", ARRAYLIST.count); // EX: In this case, it has count : 30

//In viewdidload, I get array that I saved before 
userCategory = [NSUserDefaults standardUserDefaults];
arrayNewCategory = [[NSMutableArray alloc] initWithArray: [userCategory objectForKey:@"newCategory"]];
ARRAYLIST = arrayNewCategory;
NSLog(@"ARRAYLIST 2:%d", ARRAYLIST.count); // In this moment, it only has count: 29.

我不明白为什么重新加载的数组只有29项而不是我期望的30项。

1 个答案:

答案 0 :(得分:1)

将数组保存到plist:

[array writeToFile:path atomically:NO]

并检索它:

NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];