基于Core Data的iPhone应用程序的默认数据集 [英] Default dataset for Core Data based iPhone application

查看:131
本文介绍了基于Core Data的iPhone应用程序的默认数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个使用Core Data来持久化模型的iPhone 3.0应用程序。我希望应用程序与默认数据集一起安装。当为iPhone& 3.0我使用SQL脚本在运行构建之前初始化数据库,然后将准备好的.sqlite文件部署为应用程序资源。使用Core Data的最好方法是什么。

I am writing an iPhone 3.0 application that uses Core Data to persist the model. I'd like the application to be installed with a default dataset. When developing for iPhone < 3.0 I used an SQL script to initialize a database prior to running a build and then deployed the prepared .sqlite file as an application resource. What's the best approach with Core Data.

结论:最后我写了一个通用的XML处理程序。元素名称映射到Objective-C类名称和属性名称。元素中的PCDATA值转换为由元素命名的属性上声明的类型。子元素或属性元素已解析为对象实例,因此通过解析XML文档构建了对象图。我必须首先抓住Objective-C运行时: - )

A conclusion: In the end I wrote a generic XML handler. Element names are mapped to Objective-C class names and property names. PCDATA values within elements were converted into the type declared on the property named by the element. Child elements or property elements were resolved to object instances - and thus through parsing an XML document an object graph was built. I had to get to grips with the Objective-C runtime first though :-)

目标类示例:

@interface Widget : NSObject {
@private
    NSString* name;
    NSSet* sprockets;
}
@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSSet* sprockets;
- (void)addSprocketsObject:(Sprocket*)value;    
@end

@interface Sprocket : NSObject {
@private
    NSString* name;
    NSNumber* canFly;
    NSNumber* wheels;
}
@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSNumber* canFly;
@property (nonatomic, retain) NSNumber* wheels;
@end

示例默认数据:

<data>
    <Sprocket id="sprocket-1">
        <name>Sprocket1</name>
        <wheels>4</wheels>
    </Sprocket>
    <Widget id="widget-1">
        <name>MyWidget</name>
        <sprockets>
            <Sprocket ref-id="sprocket-1"/>
            <Sprocket id="sprocket-2">
                <name>Sprocket2</name>
                <canFly/>
            </Sprocket>
            <Sprocket id="sprocket-3">
                <name>Sprocket3</name>
            </Sprocket>
        </sprockets>
    </Widget>
</data>


推荐答案

b
$ b

Two options spring to mind:


  1. 从一些合理的数据格式(XML,JSON等)编写一个导入器,并在首次运行时将其导入到您的Core Data上下文,然后将上下文保存

  2. 如果您的应用程序只需要一个持久存储,则可以预先填充它,并使用应用程序的资源部署持久存储。如果你需要多个持久存储,所有预先填充相同的默认数据,选项1可能会更容易,但你可以使用NSPersistenStoreCoordinator的migratePersistentStore:toURL:options:withType:error:(或iPhone Core Data -

在我的经验中,代码实现选项1是几乎相同的代码,所需的预填充持久存储,所以也许真的只有一个选项与两个观点。

In my experience the code to implement option 1 is nearly the same code as required to prepopulate a persistent store, so perhaps there's really only one option with two points of view.

这篇关于基于Core Data的iPhone应用程序的默认数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆