无法将 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"];
}
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, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
return [docDirectory stringByAppendingPathComponent:@"bookmarks"];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的字典里有什么?只有某些基础对象可以写出和读回,而无需您做任何额外的工作。如果您的字典包含您定义的自定义对象,则需要使用另一种机制来写入和读回数据,例如 NSArchiver。我猜测
[dataInstance Chapter]
产生的任何内容都不属于这些基本对象类型。有关可自动读写的数据类型,请参阅 NSDictionary 的
writeToFile:atomically:
文档。另请参阅 NSArchiver 和 NSCoding 协议。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.