我在 NSUserDefault 中保存了一个带有自定义对象的 nsmutable 数组。但是,当我检索对象时,我得到了一个包含对象的数组,但是当我尝试遍历对象时,应用程序崩溃并且在本地调试器中我变得无效
CFStringRef 和日志 -[消息标题]:无法识别的选择器发送到实例 0x187900。
我的自定义对象遵循 NSCoding 协议,如果我打印出数组,则以十六进制显示对象和内存分配。
我的讯息。我已将名称更改为用于测试的属性:
#import "Message.h"
@implementation Message
@synthesize tittel, adresse, dato;
static NSString *titleKey = @"title";
static NSString *urlKey = @"url";
static NSString *dateKey = @"date";
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if (self != nil) {
self.tittel = [decoder decodeObjectForKey:titleKey];
self.adresse = [decoder decodeObjectForKey:urlKey];
self.dato = [decoder decodeObjectForKey:dateKey];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.tittel forKey:titleKey];
[encoder encodeObject:self.adresse forKey:urlKey];
[encoder encodeObject:self.dato forKey:dateKey];
}
-(void)dealloc{
[dato release];
[tittel release];
[adresse release];
[super dealloc];
}
@end
我保存并尝试检索对象的方法:
-(void)saveToFile:(NSMutableArray *)incoming{
NSUserDefaults *standardUserDefault = [NSUserDefaults standardUserDefaults];
if (standardUserDefault) {
[standardUserDefault setObject:[NSKeyedArchiver archivedDataWithRootObject:[NSArray arrayWithArray:incoming]] forKey:@"Messages"];
[standardUserDefault synchronize];
}
NSLog(@"Messages array saved. (%d message in array)",[incoming count]);
}
-(NSMutableArray*)returnFromFile{
NSUserDefaults *standardUserDefault = [NSUserDefaults standardUserDefaults];
NSData * dataCheck = [[NSData alloc]initWithData:[standardUserDefault objectForKey:@"Messages"]];
NSMutableArray *retro;
if(dataCheck != nil){
NSArray *load = [NSKeyedUnarchiver unarchiveObjectWithData:dataCheck];
if(load != nil){
retro = [NSMutableArray arrayWithArray:load];
}
else
retro = [[NSMutableArray alloc]init];
}
NSLog(@"Checking saved array (%d assignments in array)",[retro count]);
for(Message *m in retro){
NSLog(@"%@", m.tittel); //It crash here.
}
return retro;
}