为什么NSUserDefaults无法在iOS中保存NSMutableDictionary? [英] Why NSUserDefaults failed to save NSMutableDictionary in iOS?
问题描述
我想在NSUserDefaults
中保存一个NSMutableDictionary
对象. NSMutableDictionary
中的键类型为NSString
,值类型为NSArray
,其中包含实现NSCoding
的对象的列表.每个文档的NSString
和NSArray
都符合NSCoding
.
I'd like to save an NSMutableDictionary
object in NSUserDefaults
. The key type in NSMutableDictionary
is NSString
, the value type is NSArray
, which contains a list of object which implements NSCoding
. Per document, NSString
and NSArray
both are conform to NSCoding
.
我收到此错误:
[NSUserDefaults setObject:forKey:]:尝试插入类NSCFDictionary的非属性值....
[NSUserDefaults setObject: forKey:]: Attempt to insert non-property value.... of class NSCFDictionary.
推荐答案
我找到了一个替代方法,在保存之前,我使用NSKeyedArchiver
编码了以NSData
结尾的根对象(NSArray
对象).然后使用UserDefaults保存NSData
.
I found out one alternative, before save, I encode the root object (NSArray
object) using NSKeyedArchiver
, which ends with NSData
. Then use UserDefaults save the NSData
.
当我需要数据时,我读出了NSData
,并使用NSKeyedUnarchiver
将NSData
转换回对象.
When I need the data, I read out the NSData
, and use NSKeyedUnarchiver
to convert NSData
back to the object.
这有点麻烦,因为我每次都需要与NSData
进行相互转换,但这确实可行.
It is a little cumbersome, because i need to convert to/from NSData
everytime, but it just works.
以下是每个请求的一个示例:
Here is one example per request:
保存:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *arr = ... ; // set value
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arr];
[defaults setObject:data forKey:@"theKey"];
[defaults synchronize];
加载:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:@"theKey"];
NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
数组中的元素实现
@interface CommentItem : NSObject<NSCoding> {
NSString *value;
}
然后在CommentItem
的实现中,提供了两种方法:
Then in the implementation of CommentItem
, provides two methods:
-(void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:value forKey:@"Value"];
}
-(id)initWithCoder:(NSCoder *)decoder
{
self.value = [decoder decodeObjectForKey:@"Value"];
return self;
}
有人有更好的解决方案吗?
Anyone has better solution?
谢谢大家.
这篇关于为什么NSUserDefaults无法在iOS中保存NSMutableDictionary?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!