开发者

Can not save NSDictionary to a file

i think the title says all. I use some example code i found here but the file will not be created.

- (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, NSUserDomain开发者_运维技巧Mask, YES);
    NSString *docDirectory = [paths objectAtIndex:0];
    return [docDirectory stringByAppendingPathComponent:@"bookmarks"];
}


What's in your dictionary? There are only certain base objects that can be written out and read back without any additional work on your part. If your dictionary includes a custom object that you defined, you'll need to use another mechanism to write and read back the data, such a an NSArchiver. I am guessing that whatever [dataInstance chapter] yields is not among these basic object types.

See the documentation for NSDictionary's writeToFile:atomically: for the data types that can be read and written automatically. Also look at NSArchiver and the NSCoding protocol.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜