如何将其他内容保存到我的UIManagedDocument文件包中?

我在解密UIManagedDocument Apple文档时遇到了很多麻烦,特别是以下方法:

  • - (id)additionalContentForURL:(NSURL *)absoluteURL error:(NSError **)error
  • - (BOOL)readAdditionalContentFromURL:(NSURL *)absoluteURL error:(NSError **)error
  • - (BOOL)writeAdditionalContent:(id)content toURL:(NSURL *)absoluteURL originalContentsURL:(NSURL *)absoluteOriginalContentsURL error:(NSError **)error

是否有人成功地将额外的内容保存到UIManagedDocument包内的“添加内容”目录中? 我正在考虑使用UUID作为文件名(具有正确的文件扩展名),将直接的图像(PNG,JPEG等)和video(m4v等)保存到此目录中,并将对这些单独文件的引用作为NSString文件path我的持久性商店。

值得一提的是苹果DTS帮助我理解这个课程。 我在这里分享了他们帮助我的一些例子(略作修改)。

OK,所以基本上它是这样工作的:子类UIManagedDocument ,并实现以下方法(其中extraInfo属性只是在我们的子类上实现的NSDictionary):

 - (BOOL)readAdditionalContentFromURL:(NSURL *)absoluteURL error:(NSError **)error { NSURL *myURL = [absoluteURL URLByAppendingPathComponent:@"AdditionalInformation.plist"]; self.extraInfo = [NSDictionary dictionaryWithContentsOfURL:myURL]; return YES; } - (id)additionalContentForURL:(NSURL *)absoluteURL error:(NSError **)error { if (!self.extraInfo) { return [NSDictionary dictionaryWithObjectsAndKeys: @"Picard", @"Captain", [[NSDate date] description], @"RightNow", nil]; } else { NSMutableDictionary *updatedFriendInfo = [self.extraInfo mutableCopy]; [updatedFriendInfo setObject:[[NSDate date] description] forKey:@"RightNow"]; [updatedFriendInfo setObject:@"YES" forKey:@"Updated"]; return updatedFriendInfo; } } - (BOOL)writeAdditionalContent:(id)content toURL:(NSURL *)absoluteURL originalContentsURL:(NSURL *)absoluteOriginalContentsURL error:(NSError **)error { if (content) { NSURL *myURL = [absoluteURL URLByAppendingPathComponent:@"AdditionalInformation.plist"]; [(NSDictionary *)content writeToURL:myURL atomically:NO]; } return YES; } 

UIManagedDocument将在需要时调用这些方法,自动将所需保存的任何内容保存到AdditionalContent目录中的文档包中。

如果您需要强制保存,只需在您的UIManagedDocument实例上调用以下内容:

 [self updateChangeCount:UIDocumentChangeDone]; 

目前,我没有使用这个图像和video – 但这个例子应该足够让你走了。

-additionalContentForURL:error:的文档指示返回一个nil应该表示错误。

  A return value of nil indicates an error condition. To avoid generating an exception, you must return a value from this method. If it is not always the case that there will be additional content, you should return a sentinel value (for example, an NSNull instance) that you check for in writeAdditionalContent:toURL:originalContentsURL:error:. 

我重写-writeContents:andAttributes:safelyToURL:forSaveOperation:error:为了另一个目的(做一些东西,首先保存一个新的文档),并调用超调用NSException神,因为contents值是零,而不是一个NSDictionary看起来像UIManagedDocument 。 嗯。

你懂得越多…

PS我想这取决于一天的时间与-writeContents:andAttributes:…它曾经抛出一个exception抱怨期待一个NSDictionary,但后来抛出一个exception抱怨,我没有通过它一个NSData。 我的眉毛不能像现在这样以更像Spock的方式被提升。