persistence - 使用 iCloud 共享 plist 文件

标签 persistence plist icloud nsfilewrapper uidocument

我有一个相对简单的应用程序,它将数据保存到位于文档文件夹中的 plist 文件中。数据在启动时加载到 UITableView 中。然后用户可以编辑、删除或添加记录,任何更改都会保存回 plist 文件。

现在我想使用 iCloud 跨设备共享这些数据(plist 文件)。我查看了文档,我的理解是我需要创建一个 UIDocument 来“管理” plist 文件。

我看过几个 iCloud 教程,但是它们都在 UIDocument 类的属性中存储一个简单的字符串,而不是整个文件(如 plist)。

如何使用 UIDocument 对象将我的 plist 文件(或任何其他文件,就此而言)共享到 iCloud?

我会将 plist 文件内容转换为 NSData,然后将其保存在 UIDocument 的属性中吗?我应该改用 NsFileWrapper 吗?

我似乎很难把头放在 UIDocument/iCloud 安排上。我可能让这变得更复杂了。

最佳答案

不确定是否有人仍然需要解决方案,但我找到了一个很好的方法来让它工作。

由于 UIDocument 只接受数据作为 NSData 或 NSFilewrapper,我首先为 NSDictionary 类创建了一个 Category,它从 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 )

如果您现在在 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 秒。

关于persistence - 使用 iCloud 共享 plist 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8409151/

相关文章:

ios - Cloudkit 公共(public)数据库错误 : "WRITE operation not permitted"

ios - 存储位置相同时如何处理 NSPersistentStoreCoordinatorStoresWillChangeNotification

core-data - 将新的核心数据模式发布到 iCloud 生产

java - JPA:更新祖父实体时如何更新孙子实体?

ios - 在构建时覆盖 NSUserDefault 首选项

cryptography - iTunes Music Store 购买参数

swift - 将 UIImage 保存到 plist 问题(SWIFT)

java - 在一个相对较大的应用程序中应该如何使用实体管理器来管理数据库事务?

ruby-on-rails - 在 Ruby on Rails 中,如何处理必须保存在数据库中但不是正确模型的数据?

java - Hibernate 持久对象行为