20

嗨,我正在尝试从餐馆对象创建一个fourates 列表,我的应用程序有一个不同餐馆的列表,我希望用户能够添加最喜欢的餐馆,但此代码不起作用

- (IBAction)toggleFav:(id)sender {

    Restaurant *resto = [self restaure];

    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:resto.price forKey:@"restoPrice"];
    [dic setObject:resto.restaurantId forKey:@"restaurantId"];
    [dic setObject:resto.restoAbout forKey:@"restoAbout"];
    [dic setObject:resto.restoAddress forKey:@"restoAddress"];
    [dic setObject:resto.restoBeverages forKey:@"restoBeverages"];
    [dic setObject:resto.restoCategory forKey:@"restoCategory"];
    [dic setObject:resto.restoEmail forKey:@"restoEmail"];
    [dic setObject:resto.restoLogo forKey:@"restoLogo"];
    [dic setObject:resto.restoName forKey:@"restoName"];
    [dic setObject:resto.restoPhone forKey:@"restoPhone"];
    [dic setObject:resto.restoCity forKey:@"restoCity"];

    NSArray *dicArray = [dic allKeys];


    if([sender isSelected]){
        //...
        [sender setSelected:NO];
        NSMutableArray *array = [[[NSUserDefaults standardUserDefaults] objectForKey:@"restoName"] mutableCopy];
        [array removeObject:dicArray];
        [[NSUserDefaults standardUserDefaults] setObject:array forKey:@"restoName"];

    } else {
        //...
        [sender setSelected:YES];
        NSMutableArray *array = [[[NSUserDefaults standardUserDefaults] objectForKey:@"restoName"] mutableCopy];
        [array addObject:dicArray];
        [[NSUserDefaults standardUserDefaults] setObject:array forKey:@"restoName"];
        [[NSUserDefaults standardUserDefaults] synchronize];

       //NSLog(@"%@",[[NSUserDefaults standardUserDefaults] stringForKey:@"restoName"]);
  }
}

' 类 '__NSCFArray'。请注意,属性列表中的字典和数组也必须只包含属性值。

4

2 回答 2

58

如果您不想费心确保所有字典值都是属性列表类型,那么您可以简单地将字典转换为 NSData,

NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
[def setObject:[NSKeyedArchiver archivedDataWithRootObject:self.myDictionary] forKey:@"MyData"];
[def synchronize];

并从沙盒返回字典:

NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
NSData *data = [def objectForKey:@"MyData"];
NSDictionary *retrievedDictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];
self.myDictionary = [[NSDictionary alloc] initWithDictionary:retrievedDictionary];

希望这可以帮助某人。:D


附加说明:如果您要获取可变字典或可变数组,请记住使用“mutableCopy”方法。否则,您无法从检索到的字典/数组中添加或删除对象。例如:

NSMutableDictionary *retrievedDictionary = 
[[NSKeyedUnarchiver unarchiveObjectWithData:data] mutableCopy];

或者

NSMutableArray *retrievedArray = 
[[NSKeyedUnarchiver unarchiveObjectWithData:data] mutableCopy];
于 2014-01-30T09:05:18.560 回答
18

您只能在 NSUserDefaults 中存储属性列表类型(数组、数据、字符串、数字、日期、字典)或 url。您需要将模型对象转换为这些对象。

于 2013-04-07T00:12:28.290 回答