2011-04-11 59 views
2

我想在NSMutableDictionary中存儲自定義對象。當我從NSMutableDictionary中讀取對象時,保存時總是爲空。在NSMutableDictionary中存儲自定義對象

下面是代碼

//保存

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 

CustomObject *obj1 = [[CustomObject alloc] init]; 
obj1.property1 = @"My First Property"; 

[dict setObject:obj1 forKey:@"FirstObjectKey"]; 
[dict writeToFile:[self dataFilePath] atomically:YES]; 

//讀取

NSString *filePath = [self dataFilePath]; 
     NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath]; 

     CustomObject *tempObj = [dict objectForKey:@"FirstObjectKey"]; 

     NSLog(@"Object %@", tempObj); 
     NSLog(@"property1:%@,,tempObj.property1); 

我怎麼能存儲的NSMutableDictionary自定義類的對象?

+0

NSLog輸出告訴你什麼?你能讀取該文件來驗證你的對象是否正確寫入它? – alesplin 2011-04-11 18:59:06

+0

2011-04-11 19:31:14.386持久性[1757:207] Object(null) 2011-04-11 19:31:14.388持久性[1757:207] property1:(null) – Leo 2011-04-11 19:05:31

+0

' - [NSDictionary writeToFile:原子地:]'返回一個'BOOL'。檢查結果是否發生在你身上? – 2011-04-11 19:23:32

回答

2

writeToFile方法只能將標準類型的對象存儲到plist中。如果你有自定義對象,你必須使用NSKeyedArchiver/NSKeyedUnarchiver

+0

嗨Eimantas,我已經實現NSKeyedArchiver方法,我現在可以保存自定義對象。我的問題是我可以像nsdictionary一樣使用它。我的意思是在NSDictionary中內置了函數來獲取所有的密鑰,這樣你可以通過ecumerate。我可以枚舉歸檔對象aswel嗎? – Leo 2011-04-11 19:57:44

+0

除非您將對象存檔爲對象(即使用encodeWithCoder而不是writeToFile),否則不是真的。 – Eimantas 2011-04-12 04:15:00

7

問題不在於將對象放入字典中;問題在於將它寫入文件。

您的自定義班級必須是serializable。您需要實施NSCoding protocol,以便Cocoa知道如何處理您的課程,當您要求將其寫入磁盤時。

這很簡單;你需要實現兩個方法,看起來類似以下內容:

- (id)initWithCoder:(NSCoder *)coder { 
    self = [super init]; 
    // If inheriting from a class that implements initWithCoder: 
    // self = [super initWithCoder:coder]; 
    myFirstIvar = [[coder decodeObjectForKey:@"myFirstIvar] retain]; 
    mySecondIvar = [[coder decodeObjectForKey:@"mySecondIvar] retain]; 
    // etc. 

    return self; 
} 

- (void)encodeWithCoder:(NSCoder *)coder { 
    // If inheriting from a class that implements encodeWithCoder: 
    // [super encodeWithCoder:coder]; 
    [coder encodeObject:myFirstIvar forKey:@"myFirstIvar"]; 
    [coder encodeObject:mySecondIvar forKey:@"mySecondIvar"]; 
    // etc. 
} 

基本上你只是列出你需要保存實例變量,然後讀取它們回正常。

更新:如Eimantas所述,您還需要NSKeyedArchiver。爲了節省:

NSData * myData = [NSKeyedArchiver archivedDataWithRootObject:myDict]; 
BOOL result = [myData writeToFile:[self dataFilePath] atomically:YES]; 

要重新加載:

NSData * myData = [NSData dataWithContentsOfFile:[self dataFilePath]]; 
NSDictionary * myDict = [NSKeyedUnarchiver unarchiveObjectWithData:myData]; 

我認爲應該這樣做。

+0

嗨喬希,我已經實現了NSCoding,仍然無法保存在字典中的對象。正如邁克所說,我檢查了寫入文件的結果,結果爲「否」。任何想法? – Leo 2011-04-11 19:40:10

+0

@Leo:沒錯,對不起。 Eimantas提到了你需要的另一半:'NSKeyedArchiver'。我已經更新了我的答案以包含該部分。 – 2011-04-11 20:39:56

相關問題