之前写过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. } }
原文链接:https://www.f2er.com/swift/320983.html