在我的应用中,每次用户创建新组时,都会创建此代码(JSON):
{"group a":"0864797073"}
...然后代码保存在名为groups.txt
的文件的目录中...但是当用户创建另一个组时,我希望以这种方式修改文件:
{"group a":"0864797073"}
{"group b":"0864797073"}
......然后......
{"group a":"0864797073"}
{"group b":"0864797073"}
{"group c":"0864797073"}
...所以添加一个新行,而不是替换文件。
我该怎么做?
提前感谢您的帮助。
编辑2:
NSString * destDir = [NSString stringWithFormat:@“/ Apps / Quick Homework& business /%@ /”,namegroup.text];
NSString *filename5 = namegroup.text;
NSString *filename6 = @"group";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *groupPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", filename6]];
NSMutableArray *titles = [NSMutableArray array];
[titles addObject:filename5];
NSMutableArray *keys = [NSMutableArray array];
[keys addObject:filename6];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:titles forKeys:keys];
NSString *jsonString = [dict JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding: NSUTF8StringEncoding];
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:groupPath];
[myHandle seekToEndOfFile];
[myHandle writeData:jsonData];
[myHandle closeFile];
[jsonData writeToFile: groupPath atomically: YES];
[[self restClient] uploadFile:filename6 toPath:destDir
withParentRev:nil fromPath:groupPath];
答案 0 :(得分:2)
如果您只想在现有文件的末尾添加一行,则可以使用以下代码。
NSData *newGroupData = [newGroupString dataUsingEncoding:NSUTF8StringEncoding];
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
[myHandle seekToEndOfFile];
[myHandle writeData:newGroupData];
[myHandle closeFile];
由您决定newGroupString
和filePath
答案 1 :(得分:0)
您执行以下操作