我目前正在后台线程中将一些文件写入磁盘,只需调用
dispatch_async(my_queue,^{
[self writeToRoot:filename data:data];
};
- (BOOL)writeToRoot:(NSString *)path data:(NSData *)content
{
NSString *fullPath = [[self rootPath] stringByAppendingPathComponent:path];
NSString *pathWithoutFile = [fullPath stringByDeletingLastPathComponent];
BOOL directoryExists = [[NSFileManager defaultManager] fileExistsAtPath:pathWithoutFile];
if (!directoryExists) {
NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:pathWithoutFile
withIntermediateDirectories:YES
attributes:nil error:&error];
NSParameterAssert(error == nil);
}
return [content writeToFile:fullPath atomically:NO];
}
我这样做是因为它不会阻塞主线程。我的问题是如何确保线程安全。在执行此后台操作时,当我尝试通过调用从磁盘读取文件时会发生什么:
[NSData dataWithContentsOfFile:fullPath];
内容会被破坏吗?还是写操作会锁定文件,而读操作会等到写入完成?