ios writetofile 在真机中失败原因

来源:互联网 发布:cyberduck for mac 编辑:程序博客网 时间:2024/06/18 10:52

You can't edit files in your main bundle. You have to first save the file to the applications documents folder then make any changes.

不能直接操作 mainbundle 主目录   ,你要存的东西应该放到 document 文件夹中  ,或者library文件夹中.

因为应用是在沙箱(sandbox)中的,在文件读写权限上受到限制,只能在几个目录下读写文件:

  • Documents:应用中用户数据可以放在这里,iTunes备份和恢复的时候会包括此目录
  • tmp:存放临时文件,iTunes不会备份和恢复此目录,此目录下文件可能会在应用退出后删除
  • Library/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除

Here's some code to maybe fix your issue:

First save the text to a directory you create:

NSString *myFilePath = [[NSBundle mainBundle]                            pathForResource:@"MyFile"                            ofType:@"txt"];NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);NSString *directory = [NSString stringWithFormat:@"%@/Some_Directory", [paths objectAtIndex:0]];// Check if the directory already existsif (![[NSFileManager defaultManager] fileExistsAtPath:directory]) {    // Directory does not exist so create it    [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil];} NSData *data = [[NSData dataWithContentsOfFile:myFilePath] retain];NSString *filePath = [[directory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [myFilePath lastPathComponent]]] retain];NSError *error = nil;if (![data writeToFile:filePath options:NSDataWritingFileProtectionNone error:&error]) {    [data writeToFile:filePath atomically:NO];}[data release];[filePath release];
0 0
原创粉丝点击