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 playimport UIKitimport CoreData// Core Data Stack Setup for In-Memory Storepublic 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 Entitylet ent = NSEntityDescription.insertNewObjectForEntityForName("Entity", inManagedObjectContext: context)
ent.setValue("fasf", forKey: "name")try! context.save()// Perform a fetch requestlet fr = NSFetchRequest(entityName: "Entity")let result = try! context.executeFetchRequest(fr)print(result)

結果如圖 

參考鏈接

作者: HuminiOS - 極光( JPush 爲極光團隊賬號,歡迎關注)

原文: http://www.jianshu.com/p/818c063cf686

知乎專欄:極光日報


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章