2012-04-25 148 views
0

我正在學習iPhone開發,並面臨讀/寫plist文件的問題。我遵循iPhone開發手冊中的一個例子,但在運行時不斷收到錯誤消息。在iPhone上閱讀/寫作plist iOS 5

該錯誤消息表示:2012-04-26 00:21:09.759 FileHandling [5915:207] - [__ NSCFDictionary ADDOBJECT:]:無法識別的選擇發送到實例0x685ac40

下面是示例代碼(它似乎細到我...雖然):

NSString *plistFileName = [[self documentPath] stringByAppendingPathComponent: @"Apps.plist"]; 
NSLog(@"Where is the file? => %@", plistFileName); 

if ([[NSFileManager defaultManager] fileExistsAtPath:plistFileName]) { 
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistFileName]; 

    for (NSString *category in dict) { 
     NSLog(@"%@", category); 
     NSLog(@"========="); 

     NSArray *titles = [dict valueForKey:category]; 

     for (NSString *title in titles) { 
      NSLog(@"%@", title); 
     } 
    } 
} else { 
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Apps" ofType: @"plist"];  
    NSLog(@"%@", plistPath); 
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile: plistPath]; 
    NSLog(@"Let's take a look : %@", dict); 
    NSMutableDictionary *copyOfDict = [dict mutableCopy]; 
    NSLog(@"Let's look at the mutable dictationary : %@", copyOfDict); 
    NSArray *categoriesArray = [[copyOfDict allKeys] sortedArrayUsingSelector: @selector(compare:)]; 

    for (NSString *cateogry in categoriesArray) { 
     NSArray *titles = [dict valueForKey: cateogry]; 
     NSMutableArray *mutableTitles = [titles mutableCopy]; 

     [mutableTitles addObject: @"New App Title"]; 

     [copyOfDict setObject: mutableTitles forKey:cateogry]; 
    } 

    NSString *fileName = [[self documentPath] stringByAppendingPathComponent: @"Apps.plist"]; 
    [copyOfDict writeToFile: fileName atomically:YES]; 
} 

回答

1

根據錯誤信息,問題是在呼叫發生的addObject:__NSCFDictionary。這意味着,在運行時,字典會收到一條消息來添加一個對象。

但是,在這段代碼中,addObject:顯然是發送到NSMutableArray。這可能意味着您在最後一個for循環中從dict檢索的每個對象titles不是數組,而是實際上是另一個字典,您的代碼只是將其稱爲數組。

確實,你的代碼看起來確實很好,所以檢查源plist的格式;用純文本編輯器打開它。另外,您使用日誌記錄,因此請確認:在輸出中,字典(包括根條目)由{curly = braces}表示,其中數組表示爲(round parentheses)