zoukankan      html  css  js  c++  java
  • 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)
    
    

    结果如图

    参考链接

    作者:HuminiOS - 极光开发者
    原文:http://www.jianshu.com/p/818c063cf686
    知乎专栏:极光日报

  • 相关阅读:
    [PHP] PHP1 与 CGI
    [PHP] Phalcon操作示范
    [Shell] swoole_timer_tick 与 crontab 实现定时任务和监控
    [PHP] Phalcon应用升级PHP7记录
    [GNU] 喝一杯咖啡, 写一写 Makefile
    [PHP] Xhprof 非侵入式使用指南
    [PHP]OOP两类写法的性能对比
    [OSI] 网络间通信流程
    [OSI] 网络7层模型的理解
    [Tools] Vim 插件管理
  • 原文地址:https://www.cnblogs.com/jpush88/p/6524493.html
Copyright © 2011-2022 走看看