swift iOS10 之CoreData 简化

iOS10之前,需要手动获取上下文对象

 

//MARK:    获取上下文对象,自定义函数,以便调用

    func getContext() -> NSManagedObjectContext{

        let appDelegate = UIApplication.shared.delegate as! AppDelegate

        return appDelegate.persistentContainer.viewContext

        

    }

 

 

 

iOS10 之后  不需要自己手动获取 , 可以直接调用viewContext

 

// 插入数据

func insertData(){

    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    myClassInfo = Class(context: appDelegate.persistentContainer.viewContext)

    myClassInfo.classNo = 12343213

    myClassInfo.name = "nihao"

    appDelegate.saveContext()

    

}

//获取数据

func fetchData(){

    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    do {

        myClass = try appDelegate.persistentContainer.viewContext.fetch(Class.fetchRequest())

    } catch  {

        print(Error.self)

    }

}

posted @ 2017-10-18 19:52  小炮陈  阅读(300)  评论(0编辑  收藏  举报