简体   繁体   English

NSUserDefaults:返回整数,不返回NSArray

[英]NSUserDefaults: returning integer, not returning NSArray

I'm trying to store both an integer and NSArray with the NSUserDefaults, but I only can correctly retrieve the integer. 我正在尝试将一个整数和NSArray与NSUserDefaults一起存储,但我只能正确检索该整数。 When I try to recover the NSArray, it returns an empty array. 当我尝试恢复NSArray时,它返回一个空数组。

I start with a custom class XMLParser.m. 我从一个自定义类XMLParser.m开始。

//XMLParser.m //XMLParser.m

//NSArray 'stored' correctly contains 10 data objects. 'stored' is an NSArray property of the XMLParser class
numberOfEvents = [stored count];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:stored forKey:@"eventsList"];
[defaults setInteger:numberOfEvents forKey:@"numberOfEvents"];
[defaults synchronize];

But when I try to access the data in another class, ie. 但是当我尝试访问另一个类中的数据时。 my AppDelegate, I get an empty NSArray 我的AppDelegate,我得到一个空的NSArray

//myApplicationAppDelegate.m
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int value = [defaults integerForKey:@"numberOfEvents"];  //returns 10
parsedEventsList = [defaults arrayForKey:@"eventsList"];  //parsedEventsList is an NSArray property of myApplicationAppDelegate class
int value2 = [parsedEventsList count]; //***returns 0***

I've even tried using 我什至尝试使用

[defaults objectForKey:@"eventsList"]

and it's still returning nothing. 而且仍然没有返回任何内容。

Thoughts? 有什么想法吗? Thanks! 谢谢!

stored数组中的所有对象都必须是属性列表对象(即NSData,NSDate,NSNumber,NSString,NSArray或NSDictionary的实例)。

Your problem appears to be that your objects are all custom. 您的问题似乎是您的对象都是自定义的。 I think you may have forgotten to make them serializable if you add code similar to this (for each of your objects) then it should work 我想如果您添加与此类似的代码(对于每个对象),您可能已经忘记使它们可序列化了,那么它应该可以工作

- (void)encodeWithCoder:(NSCoder *)encoder {

   //Encode properties, other class variables, etc
   [encoder encodeObject:self.obj1 forKey:@"obj1"];
   [encoder encodeObject:self.obj2 forKey:@"obj2"];
}

- (id)initWithCoder:(NSCoder *)decoder {
   if((self = [super init])) {
       //decode properties, other class vars
       self.obj1 = [decoder decodeObjectForKey:@"obj1"];
       self.obj2 = [decoder decodeObjectForKey:@"obj2"];
   }
return self;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM