ios writetofile 在真机中失败原因

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 exists
if (![[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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值