手机开发 2017-03-09
Playground 的出现无疑是大大的提高了开发效率,可以节省大量的编译时间。
这里介绍在 Playground 中使用 CoreData 的小技巧。
//: 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)
结果如图
参考链接
[blockquote]
作者:HuminiOS - 极光开发者 原文:http://www.jianshu.com/p/818c063cf686 知乎专栏:极光日报
[/blockquote]