Skip to content

Instantly share code, notes, and snippets.

@yusukesaitoh
Last active August 29, 2015 14:07
Show Gist options
  • Save yusukesaitoh/3d46f516d550084f09b2 to your computer and use it in GitHub Desktop.
Save yusukesaitoh/3d46f516d550084f09b2 to your computer and use it in GitHub Desktop.
iOS8でNSFileManagerのcreateFileAtPath:が失敗する
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad
{
/*
on iOS8 NSFileManager, -createFileAtPath: is not work after -changeCurrentDirectoryPath: correctly.
-contentsAtPath: and -removeItemAtPath: work fine.
iOS8でNSFileManagerの-createFileAtPath:使うとアプリがクラッシュするようになってた。
-contentsAtPath:と-removeItemAtPath:は大丈夫っぽい。
*/
[super viewDidLoad];
NSString *name = @"foo.dat";
NSData *data = [@"foo" dataUsingEncoding:NSUTF8StringEncoding];
[self saveDatFile:data name:name];
data = [self loadDatFile:name];
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
[self deleteFile:name];
}
- (void)saveDatFile:(NSData *)data name:(NSString *)name
{
NSString *dirPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager changeCurrentDirectoryPath:dirPath];
NSLog(@"%@", fileManager.currentDirectoryPath); // the correct path is logged on iOS8 or earlier.
[fileManager createFileAtPath:name contents:data attributes:nil]; // crashed on iOS8 device only.
NSString *filePath = [dirPath stringByAppendingPathComponent:name];
[fileManager createFileAtPath:filePath contents:data attributes:nil]; // setting full path is working fine on iOS8 or earlier.
}
- (NSData *)loadDatFile:(NSString *)name
{
NSString *dirPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager changeCurrentDirectoryPath:dirPath];
return [fileManager contentsAtPath:name]; // works fine.
}
- (void)deleteFile:(NSString *)name
{
NSString *dirPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager changeCurrentDirectoryPath:dirPath];
BOOL flag = [fileManager isDeletableFileAtPath:name];
if(flag == YES){
NSError *err;
[fileManager removeItemAtPath:name error:&err]; // works fine.
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment