温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-06-21 09:38:03 来源:网络 阅读:361 作者:ajkarter 栏目:移动开发

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

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

  1. 我们新建一个工程 iOS 项目工程。

  2. 点击 File -> New -> File , 在工程中新建文件 Data Model 文件 Playground 你不知道的小技巧, CoreData 的使用

  3. 在 model 中添加一个 Entitle,如下图 Playground 你不知道的小技巧, CoreData 的使用

  4. 编译工程后,在 Product 选择生成的 .app 文件,找到该目录,如下图 Playground 你不知道的小技巧, CoreData 的使用

  5. 查看包中的文件,如图 Playground 你不知道的小技巧, CoreData 的使用

  6. 可以看到一个 Mode.momd 文件, 如图 Playground 你不知道的小技巧, CoreData 的使用

  7. 在工程中新建一个 playground 文件 Playground 你不知道的小技巧, CoreData 的使用

  8. 把刚才的 Model.momd 文件拷贝到 playground 的 Resource 目录下 Playground 你不知道的小技巧, CoreData 的使用

  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)

结果如图 Playground 你不知道的小技巧, CoreData 的使用

参考链接

作者: HuminiOS - 极光( JPush 为极光团队账号,欢迎关注)

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

知乎专栏:极光日报


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI