我正在尝试将对象保存在 中NSUserDefaults
,在此站点上遇到了许多问题,但无法解决问题,我NSObject
有NSMutableArray
另一个对象。就像这里的主要对象是HotelDC
,它有一个数组“特征”一个FeactureDC
对象数组。
这是我的代码:
- (id)initWithCoder:(NSCoder *)decoder {
self = [[HotelDC alloc] init];
if (self != nil) {
self.hotel_id = [decoder decodeIntegerForKey:@"hotel_id"];
self.name = [decoder decodeObjectForKey:@"name"];
self.features = [decoder decodeObjectForKey:@"features"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeInt:hotel_id forKey:@"hotel_id"];
[encoder encodeObject:name forKey:@"name"];
[encoder encodeObject:features forKey:@"features"];//its a mutable array
}
我应该如何保存和检索?我收到错误
Attempt to insert non-property value '<HotelDC: 0xa600fe0>' of class 'HotelDC'.
Note that dictionaries and arrays in property lists must also contain only property values.
解决方案 :
//Setting
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:hotelObjSelected];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:myEncodedObject forKey:@"selectHotelObject"];
[[NSUserDefaults standardUserDefaults] synchronize];
// retrieving
NSData *data = [defaults objectForKey:@"selectHotelObject"];
hotelObjSelected = [NSKeyedUnarchiver unarchiveObjectWithData:data];