CoreData creation and use

This article is written for the first time using MarkDown syntax

Before reading this article, you can read it first This blog , understand the basic knowledge

CoreData use

Environment building

1. Check the CoreData option when creating an item

At the same time, the following code will be generated in the startup class AppDelegate class:

    // MARK: - Core Data stack
    lazy var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "CoreDataDemo")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support
    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

Also generate the file ". Xcdatamodel":

Click "Add Entity" to create an entity class:


2. CoreData option is not checked during project creation

Code

3. Management design

When creating a project, the code is automatically created in the AppDelegate file, which slows down the startup speed of the APP, so it is appropriate to design it as a single instance management class (the header file CoreData needs to be imported):

public class KYCoreData{

    var modelName: String = "KYTask"
    private static let instance: KYCoreData = KYCoreData()

    /// Get single case
    class func shared(modelName: String) -> KYCoreData {
        instance.modelName = modelName
        return instance
    }

    class func shared() -> KYCoreData {
        assert(instance.modelName != "", "modelName Cannot be empty!!!")
        return self.shared(modelName: KYCoreData.instance.modelName)
    }

    @available(iOS 10.0, *)
    lazy var storeContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: KYCoreData.instance.modelName)
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                debugPrint("Unclear error\(error)")
            }
        })
        return container
    }()

    @available(iOS 10.0, *)
    lazy var managedContext: NSManagedObjectContext = {
        return self.storeContainer.viewContext
    }()

    func saveContext() {
        if #available(iOS 10.0, *) {
            guard managedContext.hasChanges else { return }
        } else {
            // Fallback on earlier versions
        }

        do {
            if #available(iOS 10.0, *) {
                try managedContext.save()
            } else {
                // Fallback on earlier versions
            }
        } catch let error as NSError {
            debugPrint("Unclear error\(error)")
        }
    }
}

4. Add, delete, modify and query

(1) increase

    /// Insert task
    class func insert(task: KYTaskModel) -> Bool {
        var isSuccess = true
        // Step 1: get the general agent and managed object manager
        let managedContext = KYCoreData.shared().managedContext
        // Step 2: create an entity
        let entity = NSEntityDescription.entity(forEntityName: "KYTask", in: managedContext)
        let event = NSManagedObject(entity: entity!, insertInto: managedContext)
        // Step 3: save the value in the text box to person
        event.setValue(task.taskTitle, forKey: "taskTitle")
        event.setValue(task.taskDesc, forKey: "taskDesc")
        event.setValue(task.taskDate, forKey: "taskDate")
        event.setValue(task.remindTime, forKey: "remindTime")
        event.setValue(task.isComplete, forKey: "isComplete")
        event.setValue(task.taskLevel, forKey: "taskLevel")
        event.setValue(task.taskID, forKey: "taskID")
        // Step 4: save the entity to the managed object. Process if save fails
        do {
            try managedContext.save()
        } catch  {
            isSuccess = false
            fatalError("can't save")
        }
        return isSuccess
    }

(2) delete

    /// Delete a task
    class func deleteTheTask(withTaskID taskID: Int64) -> Bool {
        var isSuccess = true
        //Get data context object
        let managedContext = KYCoreData.shared().managedContext
        //Request to declare data, declare an entity structure
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "KYTask")
        //query criteria
        request.predicate = NSPredicate.init(format: "taskID == %d", taskID)
        // Asynchronous request consists of two parts: normal request and completion handler
        let async = NSAsynchronousFetchRequest(fetchRequest: request) {
            (result) in
            if (result.finalResult != nil) {
                let fetchObj = result.finalResult! as! [KYTask]
                for obj: KYTask in fetchObj {
                    managedContext.delete(obj)
                    //KYCoreData.shared().saveContext()
                }
                KYCoreData.shared().saveContext()
            }
        }
        do {
            try managedContext.execute(async)
        } catch {
            isSuccess = false
            print(error)
        }
        return isSuccess
    }

(3) reform

    /// Modify task information
    class func updateTaskInfo(task: KYTaskModel) -> Bool {
        var isSuccess = true
        let context = KYCoreData.shared().managedContext
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "KYTask")
        request.predicate = NSPredicate(format: "taskID = %d", task.taskID)
        do {
            let result = try context.fetch(request) as! [KYTask]
            result.forEach({ (event) in
                event.setTask(taskModel: task)
            })
            if context.hasChanges {
                try context.save()
            }
        } catch {
            isSuccess = false
            print(error)
        }
        return isSuccess
    }

(4) check

    /// Query task list by date
    class func queryAllTask(withDate date: String) -> [KYTaskModel] {
        let resultArr = NSMutableArray()
        // Step 1: get the general agent and managed object manager
        let managedObectContext = KYCoreData.shared().managedContext
        // Step 2: create a request for acquisition
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "KYTask")
        fetchRequest.predicate = NSPredicate(format: "taskDate = %@", date)
        //fetchRequest.resultType = .managedObjectResultType
        // Sorting, ascending: true ascending, otherwise descending
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "taskLevel", ascending: false), NSSortDescriptor(key: "remindTime", ascending: true)]
        // Step 3: execute the request
        do {
            let fetchedResults = try managedObectContext.fetch(fetchRequest) as? [NSManagedObject]
            if let results = fetchedResults {
                for model: NSManagedObject in results {
                    let task = KYTaskModel(task: model as! KYTask)
                    //print("queryAllTask found data Title ----- >% @, level:% @ d", task.taskTitle, task.taskLevel)

                    resultArr.add(task)
                }
            }

        } catch  {
            fatalError("Acquisition failure")
        }
        return resultArr as! [KYTaskModel]
    }

Tags: iOS

Posted on Sat, 04 Apr 2020 21:02:30 -0700 by Schlo_50