这里我正在读取和写入一个 json 文件。
读取正确,但当我写入文件时,它不会在 json 文件中写入数据。
这是我的代码。
//reading Json file....
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"bookmark" ofType:@"json"];
NSData *content = [[NSData alloc] initWithContentsOfFile:filePath];
NSArray *bookmarkJson=[NSJSONSerialization JSONObjectWithData:content options:0 error:nil];
//this contains array's of dictionary....
NSDictionary *newBookmark=@{@"index":@"1.1.1.1",@"text":@"Header",@"htmlpage":@"page_name"};
//take new array to add data with previous one
NSMutableArray *temp=[[NSMutableArray alloc]initWithArray:bookmarkJson];
// add object to new array...
[temp insertObject:newBookmark atIndex:0];
//now serialize temp data....
NSData *serialzedData=[NSJSONSerialization dataWithJSONObject:temp options:0 error:nil];
NSString *saveBookmark = [[NSString alloc] initWithBytes:[serialzedData bytes] length:[serialzedData length] encoding:NSUTF8StringEncoding];
//now i write json file.....
[saveBookmark writeToFile:@"bookmark.json" atomically:YES encoding:NSUTF8StringEncoding error:nil];
在“saveBookmark”(NSString)对象中,我得到了正确的文件格式,但在 bookmark.json 文件中,我没有得到任何新值。
请在这件事上给予我帮助......
编辑:正如@IulianOnofrei正确指出的那样,使用文档目录来读取/写入文件而不是资源目录。
使用这些方法来读写数据,你的问题应该可以解决:
- (void)writeStringToFile:(NSString*)aString {
// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = @"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
// The main act...
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
- (NSString*)readStringFromFile {
// Build the path...
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = @"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
// The main act...
return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}
代码来自此处找到的另一个 SO 答案:在 iPhone 上写入和读取文本文件 https://stackoverflow.com/questions/4964274/writing-and-reading-text-files-on-the-iphone
当然,第一次尝试从文档目录中读取此文件时,您将不会得到任何内容,因此第一步可能是将文件复制到那里(如果该文件不存在)。
希望这可以帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)