UIDocument & NSFileWrapper - large files taking a long time to save, despite incremental changes

╄→гoц情女王★ 提交于 2019-12-04 03:39:39

NSFileWrapper is actually loading the entire document into memory. So with a UIDocument, using an NSFileWrapper is actually not good for large documents. The documentation makes you think it does incremental saving, but in my case it didn't seem to do that.

UIDocument isn't restricted to just NSFileWrapper or NSData. You can use your own custom class, you just have to override certain methods. I ended up writing my own file wrapper class that simply refers to files on disk and reads/writes individual files on-demand.

This is what my UIDocument class looks like using the custom file wrapper:

@implementation LSDocument

- (BOOL)writeContents:(LSFileWrapper *)contents
        andAttributes:(NSDictionary *)additionalFileAttributes
          safelyToURL:(NSURL *)url
     forSaveOperation:(UIDocumentSaveOperation)saveOperation
                error:(NSError *__autoreleasing *)outError
{
    return [contents writeUpdatesToURL:self.fileURL error:outError];
}

- (BOOL)readFromURL:(NSURL *)url error:(NSError *__autoreleasing *)outError
{
    __block LSFileWrapper *wrapper = [[LSFileWrapper alloc] initWithURL:url isDirectory:NO];
    __block BOOL result;
    dispatch_sync(dispatch_get_main_queue(), ^(void) {
        result = [self loadFromContents:wrapper
                                 ofType:self.fileType
                                  error:outError];
    });
    [wrapper loadCache];
    return result;
}

@end

I use this as a base class and subclass it for other projects. It should give you an idea of what you have to do to integrate a custom file wrapper class.

I know this is a super old thread, but to help future travelers: In my case, I had a subdirectory NSFileWrapper which was not incrementally saving.

I found that if you make a copy of an NSFileWrapper, you need to set the copy's filename, fileAttributes (and possibly preferredFilename) to the original's in order for the save to be incremental. After copying those over, the contents of the subfolder would incrementally save (i.e. only write if replaced with new NSFileWrappers).

Note to Apple: Seriously, the whole NSFileWrapper API is a mess and should be cleaned up.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!