UIDocument,NSFileWrapper和Images

n.e*_*ind 6 iphone cocoa-touch nsfilewrapper icloud uidocument

我有一个UIDocument,我想由(1)一个txt文件和(2)几个jpg图像组成.我将txt和所有jpgs放入NSFileWrapper中.

当我加载UIDocument时,我需要txt文件中的信息非常快,所以我首先加载它并忽略所有图像,直到我真正需要它们.

虽然我知道如何懒洋洋地加载图像,但我不确定如何"懒洋洋地"保存图像(特别是在使用iCloud时,我不希望文件被不必要地上传/下载).假设我已经加载了所有图像并且没有更改它们.然后我想保存UIDocument,忽略所有图像(因为它们没有改变),但想要保存文本,因为它确实改变了.

我怎么做到这一点?它甚至可能吗?还是自动完成?或者我不应该将图像放在我的UIDocument中并让每个图像由不同的UIDocument处理?我害怕,这对我来说有点混乱.

到目前为止,这是我的代码,它将保存所有图像和文本(无论它们是否被更改):


UIDocument

-(id)contentsForType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {

        NSMutableDictionary *wrappers = [NSMutableDictionary dictionary];
// the following puts a wrapper into a dictionary of wrappers:
        [self encodeObject:self.text toWrappers:wrappers toFileName:@"text.data"];
        [self encodeObject:self.photos toWrappers:wrappers toFileName:@"photos.data"];
        NSFileWrapper *fileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:wrappers];

        return fileWrapper;

    }
Run Code Online (Sandbox Code Playgroud)

当我想保存UIDocument时:

[self.doc saveToURL:self.doc.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success) {
    [self.doc closeWithCompletionHandler:^(BOOL success) {}];
}];
Run Code Online (Sandbox Code Playgroud)

auc*_*uco 3

您应该在 UIDocument 实例中保留对 NSFileWrapper 的引用。这样,只有更改的内容才会被重写,而不是整个包装器。

\n\n

因此,在加载文件(或为新文档创建新文件)时保留参考:

\n\n
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError {\n    // save wrapper:\n    self.fileWrapper = (NSFileWrapper*)contents;\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在,如果您的文件确实发生了变化,您只需更新包装器:

\n\n
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError {\n    NSFileWrapper *subwrapper = [self.fileWrapper.wrappers objectForKey:@"subwrapper"];\n    if(self.somethingChanged) {\n        [self.fileWrapper.wrappers removeFileWrapper:subwrapper];\n        subwrapper = [[NSFileWrapper alloc] initRegularFileWithContents:\xe2\x80\xa6\n
Run Code Online (Sandbox Code Playgroud)\n\n

我知道代码非常简短,但我希望这有助于为您指明正确的方向。

\n