Swift CoreData增删改查

前端之家收集整理的这篇文章主要介绍了Swift CoreData增删改查前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

之前写过CoreData,现在都忘记了,不多说,直接上代码和截图,增删改查的功能都有

import UIKit
import CoreData

class ViewController: UIViewController {
    let entityName = "Person"
    let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if let path = Bundle.main.path(forResource: "testCoredataDemo",ofType: "momd") {
            if let mom = NSManagedObjectModel(contentsOf: URL(fileURLWithPath: path)) {
                let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
                managedObjectContext.persistentStoreCoordinator = psc
                if let dataPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true).last {
                    print(dataPath)
                    let path = dataPath.appending("/testCoredataDemo.sqlite")
                    do {
                        try psc.addPersistentStore(ofType: NSsqliteStoreType,configurationName: nil,at: URL(fileURLWithPath: path),options: nil)
                    } catch {
                        print(error)
                    }
                }
            }
        } else {
            print("path is error")
        }
    }
    //增
    @IBAction func insertAction(_ sender: UIButton) {
        let person = NSEntityDescription.insertNewObject(forEntityName: entityName,into: managedObjectContext) as! Person
        person.name = "First name \(10)"
        person.age = Int64(truncating: NSNumber(value: arc4random_uniform(100)))
        do {
            try managedObjectContext.save()
        } catch {
            print(error)
        }
    }
    // 删
    @IBAction func deleteAction(_ sender: UIButton) {
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
        let predicate = NSPredicate.init(format: "age = %@",NSNumber(value: 44))
        request.predicate = predicate
        do {
            let result = try managedObjectContext.fetch(request)
            result.forEach({ (person) in
                managedObjectContext.delete(person as! NSManagedObject)
            })
            print(managedObjectContext.deletedObjects)
            if managedObjectContext.hasChanges {
                try managedObjectContext.save()
            }
        } catch {
            print(error)
        }
    }
    
    // 改
    @IBAction func changeAction(_ sender: UIButton) {
        let request = NSFetchRequest<NSFetchRequestResult>.init(entityName: "Person")
        let predicate = NSPredicate(format: "age = %@",NSNumber(value: 30))
        request.predicate = predicate
        do {
            let result = try managedObjectContext.fetch(request) as! [Person]
            result.forEach({ (person) in
                person.age = 10000
            })
            print(managedObjectContext.updatedObjects)
            if managedObjectContext.hasChanges {
                try managedObjectContext.save()
            }
        } catch {
            print(error)
        }
    }
    
    // 查
    @IBAction func searchAction(_ sender: Any) {
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
        do {
            let result = try managedObjectContext.fetch(request) as! [Person]
            print(result)
            print(managedObjectContext.registeredObjects)
        } catch {
            print(error)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

猜你在找的Swift相关文章