Xcode8,Swift3,CoreData的使用

注意要添加头文件

import coredata

 //获得当前应用的AppDelegate对象
    let delegate = UIApplication.shared.delegate as! AppDelegate

    //MARK: 增加
    func insert() {
        //Entity实体
        let entity = NSEntityDescription.insertNewObject(forEntityName: "Student", into: delegate.persistentContainer.viewContext) as! Student
        entity.name = "皮卡丘"
        delegate.saveContext()
        
    }
Xcode8,Swift3,CoreData的使用_第1张图片
屏幕快照 2016-10-25 下午9.21.16.png
   func delete() {

        let request: NSFetchRequest = Student.fetchRequest()
        let entity = NSEntityDescription.entity(forEntityName: "Student", in: delegate.persistentContainer.viewContext)
        request.entity = entity
        let arr = try! delegate.persistentContainer.viewContext.fetch(request)
        for stu in arr {
            if stu.name == "zhangsan" {
                delegate.persistentContainer.viewContext.delete(stu)
                try! delegate.persistentContainer.viewContext.save()
                
            }
        }
    }
Xcode8,Swift3,CoreData的使用_第2张图片
屏幕快照 2016-10-25 下午9.21.24.png
 func update() {
        let request: NSFetchRequest = Student.fetchRequest()
        let entity = NSEntityDescription.entity(forEntityName: "Student", in: delegate.persistentContainer.viewContext)
        request.entity = entity
        let arr = try! delegate.persistentContainer.viewContext.fetch(request)
        let data = arr[3]
        data.name = "周杰伦"
        try! delegate.persistentContainer.viewContext.save()
    }
Xcode8,Swift3,CoreData的使用_第3张图片
屏幕快照 2016-10-25 下午9.21.50.png
 //MARK: 查找
    func fetch() {
 
        let request:NSFetchRequest = Student.fetchRequest()
        let entity = NSEntityDescription.entity(forEntityName: "Student", in: delegate.persistentContainer.viewContext)
        request.entity = entity
        let arr  = try! delegate.persistentContainer.viewContext.fetch(request)
        for st in arr {
            print(st.name)
        }
        
    }
Xcode8,Swift3,CoreData的使用_第4张图片
屏幕快照 2016-10-25 下午9.22.14.png

你可能感兴趣的:(Xcode8,Swift3,CoreData的使用)