iphone创建文件

来源:互联网 发布:国外用淘宝吗 编辑:程序博客网 时间:2024/06/06 12:47

注意2点:

1、创建多级目录的文件时,要先判断其目录是否存在,如果不存在就创建该目录,如果没有创建该目录,文件是不能创建成功的

2、不要使用- (BOOL)createDirectoryAtPath:(NSString *)path attributes:(NSDictionary *)attributes,这个方法在模拟器中可能能成功运行,但在设备上肯定不行的,

改用- (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(NSDictionary *)attributes error:(NSError **)error,

记得将createIntermediates设置为YES,这样就能建立多级目录了。如果是一级目录,可以设置为NO。

demo如下:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *documentsDirectory = [paths objectAtIndex:0];    NSString *strFile = [documentsDirectory stringByAppendingPathComponent:@"hello/config.plist"];    NSLog(@"strFile: %@", strFile);    NSString *strPath = [documentsDirectory stringByAppendingPathComponent:@"hello"];    if (![[NSFileManager defaultManager] fileExistsAtPath:strPath]) {        NSLog(@"there is no Directory: %@",strPath);        [[NSFileManager defaultManager] createDirectoryAtPath:strPath withIntermediateDirectories:YES attributes:nil error:nil];    }    NSArray *keys = [NSArray arrayWithObjects: @"username", @"password", @"serverName", @"serverPort", @"autoSave", nil];    NSArray *values = [NSArray arrayWithObjects: @"11", @"11", @"11", @"11", @"11", nil];    NSDictionary *configInfo = [[NSDictionary alloc] initWithObjects: values forKeys:keys];    if (![configInfo writeToFile: strFile atomically: YES]) {        NSLog(@"write file error");    }


原创粉丝点击