根据苹果的文档,NSFileManager在执行基本文件操作时是线程安全的:
“可以从多个线程安全地调用共享NSFileManager对象的方法。但是,如果使用委托接收有关移动、复制、删除和链接操作状态的通知,则应创建文件管理器对象的唯一实例,将委托分配给该对象,并使用该文件管理器启动操作。”
通常如何在后台线程上执行所有文件操作,同时仍然确保所有文件操作的执行顺序与主线程调用的顺序相同?
发布于 2015-05-29 20:30:35
您可以使用以下代码确保按所需顺序完成文件操作。我还编写了一个示例函数,它可以从任何线程调用来执行文件操作。
//this will create a queue
dispatch_queue_t _serialQueue = dispatch_queue_create("com.example.name", DISPATCH_QUEUE_SERIAL);
//call methods on different threads, to be performed one after the other.
dispatch_sync(_serialQueue, ^{ printf("1"); //call 1st method here
});
printf("2");
dispatch_sync(_serialQueue, ^{ printf("3"); //call second method here
});
printf("4");执行命令是1234
下面是一个可以调用的线程安全NSFileManager方法的示例。
-(void)threadSafeMethod{ //you can call this method from any thread and do file operations
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:sourceFile]) {
NSError *error = nil;
if (![fileManager copyItemAtPath:sourceFile
toPath:destFile
error:&error]) {
// Deal with error
}
}
}如果您查看NSFileManager的类文档,概述部分包含以下警告:
可以从多个线程安全地调用共享FileManager对象的方法。但是,如果使用委托接收有关移动、复制、删除和链接操作状态的通知,则应创建文件管理器对象的唯一实例,将委托分配给该对象,并使用该文件管理器启动操作。
无论如何,区别只是您如何启动NSFileManager,一个是使用defaultManager,另一个是分配瞬间的NSFileManager。
希望这能有所帮助。
https://stackoverflow.com/questions/23727990
复制相似问题