您的位置:首页 > 移动开发 > IOS开发

文件管理 - 2

2016-04-26 15:56 489 查看
前面讲到iOS的基本文件管理,这里做些技巧和优化的补充。

前面的创建文件并没有判断文件存不存在,这里增加一个判断文件是否存在的方法:

- (BOOL)createFolder:(NSString *)path{

BOOL isDir = NO;

NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL existed = [fileManager fileExistsAtPath:path isDirectory:&isDir];

BOOL isCreated = NO;

if (!(isDir == YES && existed == YES)){
isCreated = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
}else{
isCreated = YES;
}

return isCreated;
}

补充说明,isDir初始值赋为NO,当文件存在并且系统判断为是文件类型就会被置为YES

增加了判断文件是否存在之后,我们知道document下的文件都会被iCould备份的,如果我们不希望被iCould备份,该怎么办?

参考:http://www.cnblogs.com/macroxu-1982/p/3468030.html

代码引用至CodingNet:https://coding.net/

- (BOOL)createFolder:(NSString *)path{

BOOL isDir = NO;

NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL existed = [fileManager fileExistsAtPath:path isDirectory:&isDir];

BOOL isCreated = NO;

if (!(isDir == YES && existed == YES)){
isCreated = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
}else{
isCreated = YES;
}
if (isCreated) {
[NSURL addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:path isDirectory:YES]];
}
return isCreated;
}

宏:

#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

处理iCould备份设置:

@implementation NSURL (Common)

+(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
if ([[NSFileManager defaultManager] fileExistsAtPath: [URL path]])
{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.1")) {
NSError *error = nil;

BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES] forKey: NSURLIsExcludedFromBackupKey error: &error];

if(error){
DebugLog(@"addSkipBackupAttributeToItemAtURL: %@, error: %@", [URL lastPathComponent], error);
}
return success;
}

if (SYSTEM_VERSION_GREATER_THAN(@"5.0")) {
const char* filePath = [[URL path] fileSystemRepresentation];
const char* attrName = "com.apple.MobileBackup";
u_int8_t attrValue = 1;
int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
return result == 0;
}
}
return NO;
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS FileManager