我在 NSUserDefaults 中的这个 NSMutableArray 结构做错了什么?“尝试插入非属性列表对象" [英] What am I doing wrong with this NSMutableArray of structs in NSUserDefaults? "attempt to insert non-property list object"
问题描述
我只是想在 NSUserDefaults
中保存 NSMutableArray
/NSArray
的 struct
的 NSMutableArray
:
I'm quite simply trying to save an NSMutableArray
/NSArray
of struct
s in NSUserDefaults
:
typedef struct {
int key;
} provision;
provision p1;
p1.key = 4;
NSValue *p1Value = [NSValue value:&p1 withObjCType:@encode(provision)];
provision p2;
p2.key = 5;
NSValue *p2Value = [NSValue value:&p2 withObjCType:@encode(provision)];
NSMutableArray *provisions = [[NSMutableArray alloc] init];
[provisions addObject:p1Value];
[provisions addObject:p2Value];
[[NSUserDefaults standardUserDefaults] setObject:provisions forKey:@"Provisions"];
我遵循了此处的指南,并将所有结构存储为 NSValue
.但最后一行会导致运行时错误:
I followed the guide here and store all the structs as NSValue
. But that last line causes a runtime error:
* 由于未捕获的异常NSInvalidArgumentException"而终止应用程序,原因:* -[NSUserDefaults setObject:forKey:]:尝试插入非属性列表对象("<04000000>",<05000000>") 为关键条款'
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSUserDefaults setObject:forKey:]: attempt to insert non-property list object ( "<04000000>", "<05000000>" ) for key Provisions'
我到底做错了什么?
推荐答案
一个默认对象必须是一个属性列表,即(或对于集合实例的组合):NSData
、NSString
、NSNumber
、NSDate
、NSArray
或 NSDictionary
.如果您想存储任何其他类型的对象,您通常应该将其存档以创建一个NSData
的实例.
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
, orNSDictionary
. If you want to store any other type of object, you should typically archive it to create an instance ofNSData
.
发生异常是因为您尝试存储一个 NSValue
对象.要将结构存储为NSData
,请使用
The exception occurs because you try to store an NSValue
object.
To store the struct as NSData
, use
NSData *p1data = [NSData dataWithBytes:&p1 length:sizeof(p1)];
和提取它从NSData
和
[p1data getBytes:&p1 length:sizeof(p1)];
这篇关于我在 NSUserDefaults 中的这个 NSMutableArray 结构做错了什么?“尝试插入非属性列表对象"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!