Attempt to insert non-property value Objective C

后端 未结 2 623
失恋的感觉
失恋的感觉 2021-01-30 23:43

Hi l am trying to create a fourates lists from an restaurants Object, my application has a list of different restaurants, l want the ability for users to add favourate restauran

相关标签:
2条回答
  • 2021-01-31 00:00

    You can only store property list types (array, data, string, number, date, dictionary) or urls in NSUserDefaults. You'll need to convert your model object to those.

    0 讨论(0)
  • 2021-01-31 00:17

    If you don't want to bother about ensuring all your dictionary values are the property list types, then you can simply convert the dictionary into NSData,

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

    And to get back into a dictionary from sandbox:

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

    Hope this helps someone. :D


    ADDITIONAL NOTE: If you are getting a mutable dictionary, or mutable array, then remember to use "mutableCopy" method. Otherwise you can't add or delete objects from your retrieved dictionary/array. For example:

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

    Or

    NSMutableArray *retrievedArray = 
    [[NSKeyedUnarchiver unarchiveObjectWithData:data] mutableCopy];
    
    0 讨论(0)
提交回复
热议问题