CoreData - toant-dev/toandev.github.io GitHub Wiki
.xcdatamodeld: Manage entities, attributes...
Can use codegen to create models
- Extension to manage data
extension NSManagedObject {
class var context: NSManagedObjectContext! {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
class var request: NSFetchRequest<NSManagedObject> {
return NSFetchRequest(entityName: String(describing: self))
}
func save(success: (() -> Void)?, fail: ((Error) -> Void)?) {
guard let context = self.managedObjectContext else {
fail?(NSError(domain: "", code: 1, userInfo: nil))
return
}
if context.hasChanges {
do {
try context.save()
success?()
} catch {
fail?(error)
}
} else {
let error = NSError(domain: "Data not change", code: 0, userInfo: nil)
fail?(error)
}
}
func delete(completed: ((Error?) -> Void)?) {
self.managedObjectContext?.delete(self)
self.save(success: {
completed?(nil)
}) { (error) in
completed?(error)
}
}
class func all(predicate: NSPredicate?, success: (([NSManagedObject]) -> Void)?, fail: ((Error) -> Void)?) {
request.predicate = predicate
do {
let result = try context.fetch(request)
success?(result)
} catch {
fail?(error)
}
}
class func findByObjectId(objectId: NSManagedObjectID) -> NSManagedObject? {
do {
return try self.context.existingObject(with: objectId)
} catch {
return nil
}
}
class func findBy(predicate: NSPredicate?, success: ((NSManagedObject?) -> Void)?, fail: ((Error) -> Void)?) {
request.predicate = predicate
do {
let result = try context.fetch(request)
success?(result.first)
} catch {
fail?(error)
}
}
}
- Example
class ViewController: UIViewController {
var appDelegate: AppDelegate!
var context: NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
appDelegate = UIApplication.shared.delegate as! AppDelegate
context = appDelegate.persistentContainer.viewContext
}
func createNewUser() {
let user = Users(context: context)
user.update(username: "createNewUser", password: "passwor_3", name: "createNewUser", age: 3)
user.save(success: {
print("Create user success")
}) { (err) in
print("Create user fail: \(err.localizedDescription)")
}
}
func updateUser() {
let predicate = NSPredicate(format: "name like %@", "createNewUser")
Users.findBy(predicate: predicate, success: { user in
guard let user = user as? Users else { return }
user.update(username: "update username", password: "update password", name: "update name", age: 100)
user.save(success: {
print("Update success")
}, fail: { (err) in
print("Fetch fail cmnr: \(err)")
})
}) { (err) in
print("Fetch fail cmnr: \(err)")
}
}
}