我有这个代码。此代码不会在 Document 目录中创建文件,我不知道为什么。谁能看到我错过了什么。“数据”字典中有我需要的东西,但是当涉及到 writeToFile:它没有发生,因为没有创建文件。我拥有的其他应用程序中也可以使用相同的代码,我肯定会遗漏一些东西。
- (void)addBookmark{
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: [self filePathOfBookmarks]])
{
[self filePathOfBookmarks];
}
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: [self filePathOfBookmarks]];
if ([fileManager fileExistsAtPath: [self filePathOfBookmarks]])
{
data = [[NSMutableDictionary alloc] initWithContentsOfFile: [self filePathOfBookmarks]];
}
else
{
// If the file doesn’t exist, create an empty dictionary
data = [[NSMutableDictionary alloc] init];
}
NSMutableDictionary *firstOne = [NSMutableDictionary dictionary];
[firstOne setObject:@"one" forKey:@"name"];
[firstOne setObject:@"two" forKey:@"call"];
[firstOne setObject:@"twoandhalf" forKey:@"email"];
[firstOne setObject:@"four" forKey:@"description"];
[data setObject:firstOne forKey:@"ID"];
[data writeToFile: [self filePathOfBookmarks] atomically:YES];
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: [self filePathOfBookmarks]];
NSLog(@"file content %@",savedStock);
}
- (NSString *) filePathOfBookmarks {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
return [docDirectory stringByAppendingPathComponent:@"favourites"];
}
NSLog(@"%@",[self filePathOfBookmarks]);
这返回:
/Users/spire/Library/Application Support/iPhone Simulator/5.1/Applications/40CAA37F-6477-4101-A142-D4797748ABD9/Documents/favorites