gpt4 book ai didi

iphone - NSUserDefaults NSObject 和 NSArray 对象

转载 作者:行者123 更新时间:2023-12-03 18:39:49 25 4
gpt4 key购买 nike

我正在尝试将对象保存在NSUserDefaults中,在这个网站上经历了很多问题但无法解决问题,我的NSObject有一个 NSMutableArray另一个物体的。就像这里的主要对象是 HotelDC它有一个数组“features”,数组为 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];

最佳答案

NSUserDefaults 由属性列表支持。唉,属性列表不能包含序列化对象。引用自the manual :

A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData

您必须创建自己的序列化数据文件来直接保存对象,或者将对象序列化为允许的类型之一。令人烦恼的是,NSUserDefaults 不会调用 encodeWithCoder - 它只是筛选传递给 setObject:forKey: 的对象类型。最好的办法是自己序列化 HotelDC 的字段,或者将对象存档到 NSData 实例并存储它。

关于iphone - NSUserDefaults NSObject 和 NSArray 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14686683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com