Learning Core Data Swift 5.1
A. Writing And Reading Core Data
1. Create Core data existing project, follow this step
- create a new data model
- Add a new entity and name Entity (ex: FriendEntity -> type: String )
- in right side unchecklist optional in data model inspector
- klik entity in left side like below
2. AppDelegate
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let vc = CoreDataViewController(persistenceManager: PersistenceManager.shared)
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = UINavigationController(rootViewController: vc)
return true
}
}
3. Persistence Manager
import CoreData
import Foundation
final class PersistenceManager {
private init() {}
static let shared = PersistenceManager()
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "CoreDataModule") // "CoreDataModule" is name in CoreDataModule.xcdatamodeld
container.loadPersistentStores { _, error in
if let error = error as NSError? {
fatalError("Unresolve error \(error), \(error.userInfo)")
}
}
return container
}()
lazy var context = persistentContainer.viewContext
// MARK: Core Data Saving support
func save() {
if context.hasChanges {
do {
try context.save()
print("Save succesfully")
} catch {
let nserror = error as NSError
fatalError("Unresolve error \(nserror), \(nserror.userInfo)")
}
}
}
func fetch<T: NSManagedObject>(_ objectType: T.Type) -> [T] {
let entityName = String(describing: objectType)
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
do {
let fetchObjects = try context.fetch(fetchRequest) as? [T]
return fetchObjects ?? [T]()
} catch {
print(error)
return [T]()
}
}
}
4. Core Data class
import Foundation
import CoreData
@objc(FriendEntity)
public class FriendEntity: NSManagedObject {
}
5. Core Data properties
import CoreData
import Foundation
extension FriendEntity {
@nonobjc public class func fetchRequest() -> NSFetchRequest<FriendEntity> {
return NSFetchRequest<FriendEntity>(entityName: "FriendEntity")
}
@NSManaged public var name: String?
}
5. View Controller
import UIKit
class CoreDataViewController: UIViewController {
let persistenceManager: PersistenceManager
init(persistenceManager: PersistenceManager) {
self.persistenceManager = persistenceManager
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
createUser()
getUsers()
}
func createUser() {
let user = FriendEntity(context: persistenceManager.context)
user.name = "jakki"
persistenceManager.save()
}
func getUsers() {
let users = persistenceManager.fetch(FriendEntity.self)
users.forEach { print($0.name ?? "") }
}
}
Thanks to KILO LOCO
link video kilo loco https://www.youtube.com/watch?v=OYRo3i9z-lM
B. Updating and Deleting in Core Data
https://www.youtube.com/watch?v=XH-osAmaU5E
No comments: