使用字符串的NSUserDefault中的小麻烦

时间:2013-08-19 08:29:31

标签: iphone ios objective-c arrays nsuserdefaults

当我保存我的阵列时,每件事情都很好

NSMutableArray *savestring = news;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:savestring forKey:@"savestring"];
[defaults synchronize];

NSLog这里是一个标题,大约有10个标题(输出中很简单):

2013-08-19 11:23:13.556 Dr.Saleh[4282:1303] saveString= (
    "Sumou Real Estate Company Won The Award of the World Confederation of Business"
)
2013-08-19 11:23:13.558 Dr.Saleh[4282:1303] saveString= (
    "Biggest  indoor Mapping Projection event"
)
2013-08-19 11:23:13.559 Dr.Saleh[4282:1303] saveString= (
    "Sumou Real Estate launches"
)

.......等

然后当我加载字符串时,它只取最后一个字符串,这就是加载代码:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *loadstring = [defaults objectForKey:@"savestring"];
[defaults setValue:loadstring forKey:@"savestring"];
news = [defaults mutableArrayValueForKey:@"savestring"];

NSLog新闻只给我保存在savetring中的最后一个字符串保存在哪里

// ============================================= ============================= //

我通过更改此代码解决了我的问题

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

并使其像那样

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[[NSUserDefaults standardUserDefaults] setObject:[[[NSUserDefaults   standardUserDefaults] objectForKey:@"savestring"] arrayByAddingObject:news]     forKey:@"savestring"];

1 个答案:

答案 0 :(得分:1)

假设您的“新闻”是类型数组,标题对象就是您所指的!!!,

NSMutableArray *savestring =[[NSMutableArray alloc]initWithArray:news];
//news is an array which has the titles..
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:savestring forKey:@"savestring"];

OR

您可以直接保存它,而无需将其分配给savetring ...

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:news forKey:@"savestring"];
[defaults synchronize];