我正在尝试使用以下代码将String写入文件:
NSString *file = [[NSBundle mainBundle] pathForResource:@"settings" ofType:@"txt"];
NSLog(@"Path : , %@", file);
NSError *error=NULL;
NSString *data=@"teleiwne";
[data writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:&error];
Path的打印出来是:/ Users / kd / Library / Application Support / iPhone Simulator / 6.0 / Applications / 763B8245-CB1A-4BDE-85CF-19AEFA411DB8 / testKremala.app / settings.txt
我没有收到任何错误,但没有写入文件
我尝试了以下代码并且它有效:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"set.txt"];
NSString *data=@"Kostas";
[data writeToFile:appFile atomically:YES];
NSString *myData = [NSString stringWithContentsOfFile:appFile];
NSLog(@"Data : %@ ",myData);
答案 0 :(得分:2)
您不能写入App目录。尝试写入该app文件夹中的Documents目录。
NSString *data = @"testData";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"settings.txt"];
[data writeToFile:appFile atomically:YES];