【问题标题】:Can not save NSDictionary to a file无法将 NSDictionary 保存到文件
【发布时间】:2011-04-27 14:23:44
【问题描述】:

我认为标题说明了一切。我使用了一些在此处找到的示例代码,但不会创建该文件。

- (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"];
}

【问题讨论】:

    标签: iphone nsdictionary writetofile


    【解决方案1】:

    你的字典里有什么?只有某些基础对象可以写出和读回,而无需您进行任何额外的工作。如果您的字典包含您定义的自定义对象,您将需要使用另一种机制来写和读回数据,例如 NSArchiver。我猜[dataInstance chapter] 产生的任何东西都不属于这些基本对象类型。

    请参阅 NSDictionary 的 writeToFile:atomically: 的文档,了解可以自动读取和写入的数据类型。另请查看 NSArchiver 和 NSCoding 协议。

    【讨论】:

    • 这可能是原因!章节是自制课程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多