为什么 NSUserDefaults 无法在 iOS 中保存 NSMutableDictionary?

Why NSUserDefaults failed to save NSMutableDictionary in iOS?(为什么 NSUserDefaults 无法在 iOS 中保存 NSMutableDictionary?)

本文介绍了为什么 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.

推荐答案

我找到了一种替代方法,在保存之前,我使用 NSKeyedArchiverNSArray 对象)进行编码>,以 NSData 结尾.然后使用 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;
}

谁有更好的解决方案?

谢谢大家.

这篇关于为什么 NSUserDefaults 无法在 iOS 中保存 NSMutableDictionary?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么 NSUserDefaults 无法在 iOS 中保存 NSMutableDictionary?

基础教程推荐