Playground 你不知道的小技巧, CoreData 的使用
Playground 的出现无疑是大大的提高了开发效率,可以节省大量的编译时间。
这里介绍在 Playground 中使用 CoreData 的小技巧。
我们新建一个工程 iOS 项目工程。
点击 File -> New -> File , 在工程中新建文件 Data Model 文件
在 model 中添加一个 Entitle,如下图
编译工程后,在 Product 选择生成的 .app 文件,找到该目录,如下图
查看包中的文件,如图
可以看到一个 Mode.momd 文件, 如图
在工程中新建一个 playground 文件
把刚才的 Model.momd 文件拷贝到 playground 的 Resource 目录下
在 playground 中就可以直接使用这个 Model 资源了
//:Playground-noun:aplacewherepeoplecanplayimportUIKitimportCoreData//CoreDataStackSetupforIn-MemoryStorepublicfuncgetModelContext(name:String)->NSManagedObjectContext{//Replace"Model"withthenameofyourmodelletmodelUrl=NSBundle.mainBundle().URLForResource(name,withExtension:"momd")guardletmodel=NSManagedObjectModel.init(contentsOfURL:modelUrl!)else{fatalError("notthisfile")}letpsc=NSPersistentStoreCoordinator(managedObjectModel:model)try!psc.addPersistentStoreWithType(NSInMemoryStoreType,configuration:nil,URL:nil,options:nil)letcontext=NSManagedObjectContext(concurrencyType:.MainQueueConcurrencyType)context.persistentStoreCoordinator=pscreturncontext}letcontext=getModelContext("Model")//InsertanewEntityletent=NSEntityDescription.insertNewObjectForEntityForName("Entity",inManagedObjectContext:context)ent.setValue("fasf",forKey:"name")try!context.save()//Performafetchrequestletfr=NSFetchRequest(entityName:"Entity")letresult=try!context.executeFetchRequest(fr)print(result)
结果如图
参考链接
作者: HuminiOS - 极光( JPush 为极光团队账号,欢迎关注)
原文:http://www.jianshu.com/p/818c063cf686
知乎专栏:极光日报
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。