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

时间:2011-12-02 04:54:18

标签: ios cocoa-touch core-data uidocumentinteraction

我在解密Apple's documentation around UIManagedDocument方面遇到了很多麻烦,特别是以下方法:

  • - (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等)和视频(m4v等)保存到此目录中,并将对这些单个文件的引用存储为{{1}我的持久存储中的文件路径。

2 个答案:

答案 0 :(得分:12)

为了帮助我理解这门课,学分归Apple DTS。我正在分享他们在这里帮助我的一些例子(略有修改)。

好的,所以基本上它的工作方式如下:子类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];

目前,我没有将它用于图像和视频 - 但这个例子应该足以让你离开。

答案 1 :(得分:3)

-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:(在第一次保存新文档时做一些事情),并且调用super调用NSException之神,因为contents值为nil,而不是NSDictionary,因为看似期望的是UIManagedDocument。 HMM。

你知道的越多......

P.S。我想这取决于-writeContents:andAttributes的一天中的时间:...它曾经引发了一个抱怨期待NSDictionary的异常,但后来又抛出一个异常抱怨我没有传递NSData。我的眉毛不能以比现在更像Spock的方式被提升。