繁体   English   中英

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

[英]How do I save additional content into my UIManagedDocument file packages?

我在解决围绕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等)和视频(m4v等)保存到此目录中,并将对这些单个文件的引用存储为NSString文件路径我的持久商店。

感谢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];

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

-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 gods因为contents值为nil,而不是UDanagedDocument看似期望的NSDictionary 。 嗯。

你懂得越多...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM