ios write to disk on background thread
I am currently writing some files to disk in the background thread just by
calling
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];
}
I am doing this so as it would not block the main thread. My question is
how to ensure thread safety. while this background operation is being
carried out, what happens when I try to read from disk the file by
calling:
[NSData dataWithContentsOfFile:fullPath];
Will be content be corrupted? OR will the write operation lock the file
and the read operation will wait until the writing is completed?
No comments:
Post a Comment