为什么NSUserDefaults无法在iOS中保存NSMutableDictionary? [英] Why NSUserDefaults failed to save NSMutableDictionary in iOS?

查看:165
本文介绍了为什么NSUserDefaults无法在iOS中保存NSMutableDictionary?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在NSUserDefaults中保存一个NSMutableDictionary对象. NSMutableDictionary中的键类型为NSString,值类型为NSArray,其中包含实现NSCoding的对象的列表.每个文档的NSStringNSArray都符合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,并使用NSKeyedUnarchiverNSData转换回对象.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆