不确定是否有人仍然需要解决方案,但我找到了一个很好的方法来让它发挥作用。
由于 UIDocument 只接受 NSData 或 NSFilewrapper 形式的数据,因此我首先为 NSDictionary 类创建一个类别,该类从 NSData 返回 NSDictionary。这是该类别的两个文件:
NSDictionary+DictFromData.h:
#import <Foundation/Foundation.h>
@interface NSDictionary (DictFromData)
+ (id)dictionaryWithData:(NSData *)data;
- (id)initWithData:(NSData *)data;
@end
和 NSDictionary+DictFromData.m
#import "NSDictionary+DictFromData.h"
@implementation NSDictionary (DictFromData)
+ (id)dictionaryWithData:(NSData *)data {
return [[[NSDictionary alloc] initWithData:data] autorelease];
}
- (id)initWithData:(NSData *)data {
NSString *tmp = nil;
self = (NSDictionary *)[NSPropertyListSerialization
propertyListFromData:data
mutabilityOption:NSPropertyListImmutable
format:NULL
errorDescription:&tmp];
NSAssert1(tmp == nil,@"Error in plist: %@",tmp);
return [self retain];
}
@end
(source http://ck.kennt-wayne.de/2009/apr/nsdictionary-aus-nsdata)
如果您现在将此类别导入 UIDocument 子类中,则可以轻松加载 Plist 文件并将其保存到 iCloud 容器中。
要从 iCloud 加载 Plist,请将其添加到 UIDocument 子类中(属性内容是 NSDictionary):
- (BOOL)loadFromContents:(id)contents
ofType:(NSString *)
typeName error:(NSError **)outError {
if ([contents length] > 0){
self.contents = [NSDictionary dictionaryWithData:contents];
} else {
self.contents = nil;
}
// call some Methods to handle the incoming NSDictionary
// maybe overwrite the old Plist file with the new NSDictionary
return YES;
}
要将数据保存回 iCloud,请添加以下内容:
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError {
NSData * plistData = [[[NSData alloc]initWithContentsOfFile:YOUR_PLIST_FILE]autorelease];
return plistData;
}
如果您现在致电:
[myUIDocument updateChangeCount:UIDocumentChangeDone];
YOUR_PLIST_FILE 正在同步。请记住,您的 iCloud 容器更新大约需要 10-15 秒。