coredata:CRED

import CoreData

//添加数据
    func saveCoreDate(){
        //加载AppDelegate
        let app = UIApplication.sharedApplication().delegate as! AppDelegate
        //获取管理的上下文
        let context = app.managedObjectContext
        var error:NSError?
        //创建一个实例并给属性赋值
        let admin = NSEntityDescription.insertNewObjectForEntityForName("Admin", inManagedObjectContext: context) as! Admin
        admin.token = "1"
        //保存数据
        do {
            try context.save()
            print("success!")
        }catch let error{
            print("context can't save!, Error:\(error)")
        }
    }
    func fetchCoreData (){
        //加载AppDelegate
        let app = UIApplication.sharedApplication().delegate as! AppDelegate
        //获取管理的上下文
        let context = app.managedObjectContext
        // 声明数据请求实体
        let fetchRequest = NSFetchRequest(entityName: "Admin")
        let predicate = NSPredicate(format:"token='1'")
        //fetchRequest.predicate=predicate//设置查询条件按照id查找不设置查询条件,则默认全部查找
        //执行查询操作
        do {
            let list =
                try context.executeFetchRequest(fetchRequest) as! [NSManagedObject]
            print("打印查询结果")
            for i in list as! [Admin] {
                print(i)
                //修改操作:将查询到的结果修改后,再调用context.save()保存即可
                i.token = "1"
                //删除操作:将查询到的额结果删除后,再调用context.save()保存即可
                context.deleteObject(i)
            }
        }catch let error{
            print("context can't fetch!, Error:\(error)")
        }
        do {
            try context.save()
            print("success!")
        }catch let error{
            print("context can't save!, Error:\(error)")
        }
        
    }

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注