Playground 你不知道的小技巧,CoreData的使用

Playground 的出现无疑是大大的提高了开发效率,可以节省大量的编译时间。

这里介绍在 Playground 中使用 CoreData 的小技巧。

  1. 我们新建一个工程 iOS 项目工程。
  2. 点击File -> New -> File , 在工程中新建文件 Data Model 文件


  3. 在 model 中添加一个 Entitle,如下图


  4. 编译工程后,在 Product 选择生成的 .app 文件,找到该目录,如下图


  5. 查看包中的文件,如图


  6. 可以看到一个 Mode.momd 文件, 如图


  7. 在工程中新建一个 playground 文件


  8. 把刚才的 Model.momd 文件拷贝到 playground 的 Resource 目录下


  9. 在 playground 中就可以直接使用这个 Model 资源了
//: Playground - noun: a place where people can play

import UIKit
import CoreData

// Core Data Stack Setup for In-Memory Store
public func getModelContext(name:String) -> NSManagedObjectContext {
  
  // Replace "Model" with the name of your model
  let modelUrl = NSBundle.mainBundle().URLForResource(name, withExtension: "momd")
  guard let model = NSManagedObjectModel.init(contentsOfURL: modelUrl!) else { fatalError("not this file") }
  
  let psc = NSPersistentStoreCoordinator(managedObjectModel: model)
  try! psc.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil)
  
  let context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
  context.persistentStoreCoordinator = psc
  
  return context
}

let context = getModelContext("Model")

// Insert a new Entity
let ent = NSEntityDescription.insertNewObjectForEntityForName("Entity", inManagedObjectContext: context)
ent.setValue("fasf", forKey: "name")

try! context.save()

// Perform a fetch request
let fr = NSFetchRequest(entityName: "Entity")
let result = try! context.executeFetchRequest(fr)

print(result)

结果如图


参考链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,835评论 25 709
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,875评论 18 399
  • 仅以方便自己查阅记录前言1.静态库和动态库有什么异同?静态库:链接时完整地拷贝至可执行文件中,被多次使用就有多份冗...
    190CM阅读 4,373评论 0 4
  • git是什么?一个高端大气上档次的分布式版本控制系统。相信小伙伴们对于git 并不陌生。对它当中文件的三种状态:已...
    星期六1111阅读 487评论 2 2
  • 有人说过:“生活,就是生下来,活下去!”生活的艰辛对于每一个人来说,都是一个艰难的话题。生活对于我来说是怎样的呢,...
    墨墨大可鱼阅读 1,372评论 0 1