NSUserDefault到NSArray

时间:2012-03-08 09:01:20

标签: iphone objective-c xcode ios5

在NSUserDefault中存储了2个标签的值,并使用了NSMutableArray。

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

// Add a bookmark
NSMutableDictionary *bookmark = [NSMutableDictionary new];
[bookmark setValue:author.text forKey:@"author"];
[bookmark setValue:book.text forKey:@"book"];
[bookmarks addObject:bookmark];

// Save your (updated) bookmarks
[userDefaults setObject:bookmarks forKey:@"bookmarks"];
[userDefaults synchronize];

现在我的问题是如何检索NSAserDefault的NSArray值?

 NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
 self.dataArray = [prefs arrayForKey:@"bookmarks"];

 NSString *author =  ?? 
 NSString *book =  ??

3 个答案:

答案 0 :(得分:1)

NSString * author = [self.dataArray objectForKey: @"author"];
NSString * book = [self.dataArray objectForKey: @"book"];

假定您已成功保存数组,并且您已成功从NSUserDefaults重新加载数组。你真的应该在代码中做一些错误检查。

答案 1 :(得分:1)

在dataArray中,您可以存储大量书签。此方法可以记录所有书签。

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];  
self.dataArray = [prefs objectForKey:@"bookmarks"]; 

for(int i=0;i<[dataArray count];i++){
    NSDictionary *dic = [dataArray objectAtIndex:i];
    NSLog(@"%@",dic);
    NSString * author = [dic objectForKey: @"author"];
    NSString * book = [dic objectForKey: @"book"];  
}

答案 2 :(得分:0)

您已插入带字典的数组。您可以使用

检索它
self.dataArray = [prefs arrayForKey:@"bookmarks"];
 NSString *author =  [self.dataArray objectAtIndex:0] objectForKey:@"author"]; 
 NSString *book =   [self.dataArray objectAtIndex:0] objectForKey:@"book"];

但最好将字典直接存储在用户默认值中。