Core Data
Some time we need to use core data in application , for that we use in build core data provided by iOS but on the time of creation we select core data and default code attach to appdelegate class and its version is set to current , when we less the iOS version of application then the default code is not supported so we need such code that run from lower version to current version.
For this we need to add some code .
1: On creating a new project select core data.
2: add this code in appdelegate.swift class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 |
// // AppDelegate.swift // CoreDataText // // Created by kunal prasad on 20/02/17. // Copyright © 2017 Webkul. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var context: NSManagedObjectContext? var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack @available(iOS 10.0, *) lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "CoreDataText") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { do { return try NSPersistentStoreCoordinator.coordinator(name: "CoreDataText") } catch { print("CoreData: Unresolved error \(error)") } return nil }() lazy var managedObjectContext: NSManagedObjectContext = { let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if #available(iOS 10.0, *) { context = persistentContainer.viewContext } else { context = managedObjectContext } if (context?.hasChanges)! { do { try context?.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } } extension NSPersistentStoreCoordinator { /// NSPersistentStoreCoordinator error types public enum CoordinatorError: Error { /// .momd file not found case modelFileNotFound /// NSManagedObjectModel creation fail case modelCreationError /// Gettings document directory fail case storePathNotFound } /// Return NSPersistentStoreCoordinator object static func coordinator(name: String) throws -> NSPersistentStoreCoordinator? { guard let modelURL = Bundle.main.url(forResource: name, withExtension: "momd") else { throw CoordinatorError.modelFileNotFound } guard let model = NSManagedObjectModel(contentsOf: modelURL) else { throw CoordinatorError.modelCreationError } let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) guard let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else { throw CoordinatorError.storePathNotFound } do { let url = documents.appendingPathComponent("\(name).sqlite") let options = [ NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true ] try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options) } catch { throw error } return coordinator } } |
3: Now you can use the any function for insert or delete or update
exam:
Here is example for saving the data in core data “Person” is entity name and “name”,”age” is attribute.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
func saveName(name: String, data:String) { //1 var managedContext: NSManagedObjectContext? let appDelegate = UIApplication.shared.delegate as! AppDelegate if #available(iOS 10.0, *) { managedContext = appDelegate.persistentContainer.viewContext } else { managedContext = appDelegate.managedObjectContext } //2 let entity = NSEntityDescription.entity(forEntityName: "Person", in:managedContext!) let person = NSManagedObject(entity: entity!, insertInto: managedContext) as! Person //3 person.name = name; person.age = data; //person.setValue(name, forKey: "name") //person.setValue("10", forKey: "age") //4 do { try managedContext?.save() //5 print("save data") // people.append(person) } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } |
4: Select coredataxml file and click on editor and select create NSMangedsubclass.
5: then it will create a two file.
1: Person + CoreDataClass.swift
So write:
1 2 3 4 5 6 7 8 |
import Foundation import CoreData import UIKit public class Person: NSManagedObject { static let entityName = "Person" } |
2: Person + CoreDataProperties.swift
write this:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import Foundation import CoreData extension Person { @nonobjc public class func fetchRequest() -> NSFetchRequest<Person> { return NSFetchRequest<Person>(entityName: "Person"); } @NSManaged public var age: String? @NSManaged public var name: String? } |
6: for updation or view all .
create a Service.swift class
and write this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
// // Service.swift // CoreDataText // // Created by kunal prasad on 20/02/17. // Copyright © 2017 Webkul. All rights reserved. // import Foundation import CoreData class Service{ var context: NSManagedObjectContext init(context: NSManagedObjectContext){ self.context = context } // Creates a new Person func create(name: String, age: String) -> Person { let newItem = NSEntityDescription.insertNewObject(forEntityName: Person.entityName, into: context) as! Person newItem.name = name newItem.age = age return newItem } // Gets a person by id func getById(id: NSManagedObjectID) -> Person? { return context.object(with: id) as? Person } // Gets all. func getAll() -> [Person]{ return get(withPredicate: NSPredicate(value:true)) } // Gets all that fulfill the specified predicate. // Predicates examples: // - NSPredicate(format: "name == %@", "Juan Carlos") // - NSPredicate(format: "name contains %@", "Juan") func get(withPredicate queryPredicate: NSPredicate) -> [Person]{ let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: Person.entityName) fetchRequest.predicate = queryPredicate do { let response = try context.fetch(fetchRequest) return response as! [Person] } catch let error as NSError { // failure print(error) return [Person]() } } // Updates a person func update(updatedPerson: Person){ if let person = getById(id: updatedPerson.objectID){ person.name = updatedPerson.name person.age = updatedPerson.age } } // Deletes a person func delete(id: NSManagedObjectID){ if let personToDelete = getById(id: id){ context.delete(personToDelete) } } // Saves all changes func saveChanges(){ do{ try context.save() } catch let error as NSError { // failure print(error) } } } |
6: for update write this function:
in your viewcontroller class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
@IBAction func update_Database(_ sender: Any) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } var managedContext: NSManagedObjectContext! if #available(iOS 10.0, *) { managedContext = appDelegate.persistentContainer.viewContext } else { managedContext = appDelegate.managedObjectContext } let personService = Service(context: managedContext!) var AllData : [Person] = personService.get(withPredicate: NSPredicate(format: "name == %@", "radha")) // update the name after searching if AllData.count > 0{ let update = personService.getById(id:AllData[0].objectID) update?.name = "radha kumari"; personService.update(updatedPerson: update!) personService.saveChanges() } } |
7: For viewall data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
@IBAction func viewAll(_ sender: Any) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } var managedContext: NSManagedObjectContext! if #available(iOS 10.0, *) { managedContext = appDelegate.persistentContainer.viewContext } else { managedContext = appDelegate.managedObjectContext } //2 let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person") do { people = try managedContext.fetch(fetchRequest) if people.count > 0{ let person = people[0] print("ssss",person.value(forKeyPath: "name") as? String,people.count) print("ssss",person.value(forKeyPath: "age") as? String,people.count) } } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } } |