我怎样才能传递一个“充满对象的 MutableArray"?通过使用 NSUserDefaults 到另一个类?
如何使用 NSUserDefaults
将MutableArray
with full Objects"传递给另一个类?我知道如何传递MutableArray
",但这不起作用!
How can I pass a "MutableArray
with full of Objects" to another class by using NSUserDefaults
? I know how to pass "MutableArray
"s but this does not work!
所以;
我有一个 MutableArray;'myCityObjects
',然后我用对象填充它;'城市
'在每个 'cities
' 对象中都有诸如 cityName
、cityLocation
等属性...
I have a MutableArray; 'myCityObjects
', and I populate it with objects; 'cities
'
In each 'cities
' object there are properties like cityName
, cityLocation
etc...
[myCityObjects addObject:cities];
现在,我想要做的是使用'NSUserDefaults
'将这个MutableArray
(用对象填充)传递给另一个类;
Now, what I want to do is to pass this MutableArray
(filled with objects) to another class by using 'NSUserDefaults
';
[[NSUserDefaults standardUserDefaults] setObject: myCityObjects forKey:@"MCO"];
在另一个班级中,
NSMutableArray *getMyCityObjects = [[NSArray alloc] init];
getMyCityObjects = [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:@"MCO"];
但它不起作用!我无法在另一个类中获取 myCityObjects
,getMyCityObjects
"为空.我该如何解决?
But it doesn't work! I cannot get myCityObjects
in the other class, "getMyCityObjects
" is empty. How can I fix that?
谢谢,E.
您的数组为 nil,因为其中的对象(您的自定义对象)无法序列化.
Your array is nil because the objects in it (your custom objects) can't be serialised.
请看一下 NSCoding 协议.你想要序列化的对象(例如写入 NSUserDefaults)必须实现方法 -encodeWithCoder:
和 -initWithCoder
.
Please take a look at the NSCoding protocol. Objects you want to serialise (eg for writing to NSUserDefaults) must implement the methods -encodeWithCoder:
and -initWithCoder
.
我相信您会发现搜索我给您的术语是多么容易...
I'm sure you'll find how this is rather easily done searching for the terms I gave you...