当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Try to write a string to file

问题描述:

Possible Duplicate:

Problem in writing to a file in application bundle

I am trying to write a String to a file using the following code :

NSString *file = [[NSBundle mainBundle] pathForResource:@"settings" ofType:@"txt"];

NSLog(@"Path : , %@", file);

NSError *error=NULL;

NSString *[email protected]"teleiwne";

[data writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:&error];

The print out of Path is : /Users/kd/Library/Application Support/iPhone Simulator/6.0/Applications/763B8245-CB1A-4BDE-85CF-19AEFA411DB8/testKremala.app/settings.txt

I don't get any error but nothing is written to file

I tried the following code and it worked :

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"set.txt"];

NSString *[email protected]"Kostas";

[data writeToFile:appFile atomically:YES];

NSString *myData = [NSString stringWithContentsOfFile:appFile];

NSLog(@"Data : %@ ",myData);

网友答案:

You aren't allowed to write to the App directory. Try writing to the Documents directory inside that app folder.

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];
分享给朋友:
您可能感兴趣的文章:
随机阅读: