我正在编写一个文件,然后将 NSURLIsExcludedFromBackupKey 属性添加到文件中。为此,我的 HPSFileHelper 类中有以下两种方法:
+(void)writeDataToFileWithData:(NSData*)data andFilename:(NSString*)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
[data writeToFile:filePath atomically:YES];
NSURL* fileURL = [NSURL fileURLWithPath:filePath];
[HPSFileHelper addSkipBackupAttributeToItemAtURL:fileURL]; // Prevent this file from being backed up.
}
+(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
NSError *error = nil;
BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success){
NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
}
return success;
}
问题是 assert ... fileExistsAtPath 偶尔会失败。大概这是因为有时在断言运行时文件还没有完全写入和解锁?(对于大文件?)
我应该如何围绕这个问题编写代码?