我目前正在寫一些文件在後臺線程盤只是通過調用IOS寫入到磁盤上的後臺線程
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];
公司將內容被破壞? 或者寫入操作會鎖定文件,讀取操作會一直等到寫入完成?
這是我最終使用的解決方案。從同一隊列的磁盤寫入和讀取。非常感謝。 – wjheng