2010-05-18 73 views
2

我试图将一个对象存档到plist文件中,稍后加载它以填充tableView。 似乎该文件正确归档,但在尝试从文件中获取值时遇到了访问错误。NSKeyedUnarchiver - 访问错误

我做错了什么?

这是我保存它

// Create some phonebook entries and store in array 
NSMutableArray *book = [[NSMutableArray alloc] init]; 
Phonebook *chris = [[Phonebook alloc] init]; 
chris.name = @"Christian Sandrini"; 
chris.phone = @"1234567"; 
chris.mail = @"[email protected]"; 
[book addObject:chris]; 
[chris release]; 

Phonebook *sacha = [[Phonebook alloc] init]; 
sacha.name = @"Sacha Dubois"; 
sacha.phone = @"079 777 777"; 
sacha.mail = @"[email protected]"; 
[book addObject:sacha]; 
[sacha release]; 

Phonebook *steve = [[Phonebook alloc] init]; 
steve.name = @"Steve Solinger"; 
steve.phone = @"079 123 456"; 
steve.mail = @"[email protected]"; 
[book addObject:steve]; 
[steve release]; 

[NSKeyedArchiver archiveRootObject:book toFile:@"phonebook.plist"]; 

在这里,我试图把它弄出来的文件,并保存它放回一个数组

- (void)viewDidLoad { 
    // Load Phone Book 
    NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:@"phonebook.plist"]; 

    self.list = arr; 

    [arr release]; 
    [super viewDidLoad]; 
} 

的部分,我尝试建立一个细胞

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *PhoneBookCellIdentifier = @"PhoneBookCellIdentifier"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PhoneBookCellIdentifier]; 

    if (cell == nil) 
    { 
     cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:PhoneBookCellIdentifier] autorelease]; 
    } 

    NSUInteger row = [indexPath row]; 
    Phonebook *book = [self.list objectAtIndex:row]; 
    cell.textLabel.text = book.name; 
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; 

    return cell; 
} 

这里坏访问错误

当前语言:汽车;目前 Objective-C的断言失败:(CLS), 功能的getName,文件 /SourceCache/objc4_Sim/objc4-427.5/runtime/objc-runtime-new.mm, 线3990.断言失败:(CLS), 功能的getName,文件 /SourceCache/objc4_Sim/objc4-427.5/runtime/objc-runtime-new.mm, 线3990.断言失败:(CLS), 功能的getName,文件 /SourceCache/objc4_Sim/objc4-427.5/runtime /objc-runtime-new.mm, 线3990.断言失败:(CLS), 功能的getName,文件 /SourceCache/objc4_Sim/objc4-427.5/runtime/objc-runtime-new.mm, 线3990.

+0

我我不确定这是否是唯一的问题,但是您不应该在viewDidLoad中释放arr。 – walkytalky 2010-05-18 09:28:15

回答

2

只是为了扩大这个分数:unarchiveObjectWithFile将返回一个自动释放指针。你不在本地retain它,所以你不应该release。因为你这样做,对象随后被释放,当你通过调用book.name来使用它时,它不在那里。

(我假设self.list属性适当保留,这样的对象将只要你不要在这里释放保持周围,如果没有,你需要解决这个问题了。)

+0

你是男人;-)删除[arr发布]解决了这个问题。非常感谢! – Chris 2010-05-18 10:24:07

+0

这个答案拯救了我的一天 - 谢谢! – Micko 2011-12-04 15:21:21