2009-12-11 136 views
0

我有一個數組,我保存到NSUserDefaults,其中包含我的自定義類Assignment,它符合NSCoding協議的數組。數組保存並正確加載,我可以驗證數組的檢索到的第一個對象是類Assignment。當我嘗試訪問數組中Assignment對象的ivars時,會發生問題。它崩潰,我得到以下錯誤:NSKeyedUnarchiver對象被破壞?

*** -[CFString respondsToSelector:]: message sent to deallocated instance 0x3948d60 

這是我用來保存到用戶默認值的代碼。請注意,我還檢索並檢查保存的對象以進行調試。

-(void)saveToUserDefaults:(NSArray*)myArray 
{ 
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults]; 

    if (standardUserDefaults) { 
     [standardUserDefaults setObject:[NSKeyedArchiver archivedDataWithRootObject:myArray] forKey:@"Assignments"]; 
     [standardUserDefaults synchronize]; 
    } 
    NSLog(@"Assignments array saved. (%d assignments in array)",[myArray count]); 
    NSData *dataCheck = [[NSData alloc] initWithData:[standardUserDefaults objectForKey:@"Assignments"]]; 
    NSArray *arrayCheck = [[NSArray alloc] initWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:dataCheck]]; 
    NSLog(@"Checking saved array (%d assignments in array)",[arrayCheck count]); 
    if ([[arrayCheck objectAtIndex:0] isKindOfClass:[Assignment class]]) { 
     NSLog(@"It's of the class Assignment."); 
    } 
    Assignment *testAssignment = [[Assignment alloc] initWithAssignment:[arrayCheck objectAtIndex:0]]; 
    NSLog(@"Title: %@ Course: %@",[testAssignment title],[testAssignment course]); 
} 

一切都很好,直到我分配testAssignment,這是崩潰發生的地方。有沒有人有任何想法?

編輯:這是我的NSCoding方法的分配類:

- (void)encodeWithCoder:(NSCoder *)coder { 
    [coder encodeObject:title forKey:@"title"]; 
    [coder encodeObject:course forKey:@"course"]; 
    [coder encodeObject:dueDate forKey:@"dueDate"]; 
    [coder encodeObject:notes forKey:@"notes"]; 
} 

- (id)initWithCoder:(NSCoder *)coder { 
    self = [[Assignment alloc] init]; 
    if (self != nil) 
    { 
     title = [coder decodeObjectForKey:@"title"]; 
     course = [coder decodeObjectForKey:@"course"]; 
     dueDate = [coder decodeObjectForKey:@"dueDate"]; 
     notes = [coder decodeObjectForKey:@"notes"]; 
    } 
    return self; 
} 

回答

3

回答我自己的問題。在initWithCoder中,我需要保留所有我正在解碼的對象:

//Example  
title = [[coder decodeObjectForKey:@"title"] retain]; 

現在一切都很好用。 :)

+1

或者,如果您定義了屬性,則可以使用self隱式保留它。,即self.title = [coder decodeObjectForKey:@「title」]; – 2012-01-11 22:05:51

+1

這意味着EVERY OBJECT,顯然包括initWithCoder:methods內的對象。因此,如果unarchiver在發佈時進行了segfaulting,請通過並確保對象內部的對象,這些對象內部的對象以及這些對象內部的對象等在展開時都保留下來。 – Tustin2121 2012-02-26 05:11:42

+0

@Ben Jakuben:非常感謝,這對我很有用。 – Vjlakshmi 2012-12-07 07:45:47