【问题标题】:programmatically create new table with ios-core data以编程方式使用 ios-core 数据创建新表
【发布时间】:2012-06-09 01:14:13
【问题描述】:

Core Data 可以让我以编程方式创建新表吗?或者如果我需要,我需要直接使用 SQLite。

谢谢

【问题讨论】:

    标签: iphone ios database sqlite core-data


    【解决方案1】:

    从 CoreData 的角度来看,您并没有真正创建新表,因为数据库表只是与核心数据模型相关联的一种可能的持久性存储类型。

    但是,您可以使用 NSEntityDescription 类以编程方式创建新的核心数据实体。在 NSEntityDescription 类文档中,您会发现:

    Entity descriptions are editable until they are used by an object graph manager. This
    allows you to create or modify them dynamically. However, once a description is used 
    (when the managed object model to which it belongs is associated with a persistent store
    coordinator), it must not (indeed cannot) be changed. This is enforced at runtime: any
    attempt to mutate a model or any of its sub-objects after the model is associated with a 
    persistent store coordinator causes an exception to be thrown. If you need to modify a
    model that is in use, create a copy, modify the copy, and then discard the objects with
    the old model.
    

    我从来没有尝试在运行时修改一个,所以我不确定当你有一个现有的 SQLite 持久性存储时它到底有多好,如果有的话。但可能值得玩弄 NSEntityDescription 看看它是否能让你接近你想要做的事情。

    【讨论】:

    • 感谢 Tim,与许多 iOS 框架相比,coredata 对我来说有点习惯。
    • @shebelaw:一开始是相当复杂的,但如果你需要一个助推器,我会推荐 Big Nerd Ranch 书籍。他们把事情放在外行的术语中,他们也不拐弯抹角。 bignerdranch.com/books 在亚马逊上购买二手书可能更便宜,但仍然值得一看。
    【解决方案2】:

    您通常使用 Xcode 的数据模型设计工具以图形方式创建托管对象模型。 (如果您希望可以在运行时以编程方式构建模型

    Core Data programming Guide

    【讨论】:

    • 我认为这是不可能的。你以前在哪里可以做到这一点?
    • @Shanmugaraja G:一旦模型通过持久存储被拉入,您就不能以编程方式更改模型。但是,您可以更改未被商店“锁定”的模型。
    【解决方案3】:

    但是你可以:

    • 创建一个对象模型上下文(在您正在/使用的当前上下文之外)
    • 创建一个或多个实体
    • 为该模型创建一个单独的持久存储
    • 保存实体等...
    • 完成后关闭商店

    您无法动态更改模型,因为它们在被拉入运行时环境时几乎是固定的。

    【讨论】:

      猜你喜欢
      • 2019-08-10
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 2015-12-05
      相关资源
      最近更新 更多