2011-04-27 91 views
0

我認爲標題說的都是。我使用了我在這裏找到的一些示例代碼,但該文件不會被創建。無法保存NSDictionary到一個文件

- (id)init { 
    [[NSBundle mainBundle] loadNibNamed:@"PadContent" owner:self options:nil]; 

    if ([[NSFileManager defaultManager] fileExistsAtPath:[self filePathOfBookmarks]]) { 
     bookmarks = [[NSMutableDictionary alloc] 
         initWithContentsOfFile:[self filePathOfBookmarks]]; 
    } else { 
     bookmarks = [[NSMutableDictionary alloc] init]; 
     NSLog(@"file does not exist"); 
    } 
    return self; 
} 

- (void)addBookmark:(id)sender{ 
    [bookmarks setObject:[dataInstance chapter] forKey:[[dataInstance chapter]title]]; 
    [bookmarks setObject:[dataInstance chapter] forKey:@"test"]; 
    NSLog(@"count: %d", [bookmarks count]); 
    NSLog([self filePathOfBookmarks]); 
    [bookmarks writeToFile:[self filePathOfBookmarks] atomically:YES]; 
} 

- (NSString *) filePathOfBookmarks { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *docDirectory = [paths objectAtIndex:0]; 
    return [docDirectory stringByAppendingPathComponent:@"bookmarks"]; 
} 

回答

5

什麼是你的字典?只有某些基礎對象可以寫出來並且回讀,而無需您做任何額外的工作。如果您的字典包含您定義的自定義對象,則需要使用其他機制來寫入和讀回數據,例如NSArchiver。我猜測,無論[dataInstance chapter]產量是不是這些基本的對象類型之一。

有關可以自動讀取和寫入的數據類型,請參閱NSDictionary的文檔(文件名爲writeToFile:atomically:)。也看看NSArchiver和NSCoding協議。

+0

這可能是原因!章是一個自制課。 – madmax 2011-04-27 15:28:46