swift core data

    swift存储数据使用core data,它是一套ORM框架,苹果力荐,但是性能不及sqlite,而且除了真tm复杂我也没看到有什么亮点,不过多学点总还是好的,黑人问号。

    Xcode提供一套可视化生成Entity,但是如果按照教程去做,自动使用默认的Class生成会报错,在YourEnityproperties.swift加上@obj或者直接选none生成,手撸也不费事的

    可以自己封装一下对context使用,注意container的名字需要修改,改成当前工程名,否则会抱实体不对应的错

import Foundation
import CoreData

class DataBase {
    
    static let shared = DataBase()
    private init() {
        
    }
    
    // MARK: - Core Data stack
    
    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
         */
        let container = NSPersistentContainer(name: "PFReminder")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                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 {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}

    个人吐槽的是这玩意儿的CURD确实糟糕...尤其是删,改...

func selectAll() -> [Notification]? {
        let managedObjectContext = db.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Notification")
       
        do {
            let fetchedResults = try managedObjectContext.fetch(fetchRequest) as? [Notification]
            return fetchedResults
        } catch {
            fatalError("获取失败")
        }
    }
    
    func saveNotification(title: String, body: String) {
        let date = DateUtil().getCurentDate()
        let managedObjectContext = db.persistentContainer.viewContext
       
        let entity = NSEntityDescription.entity(forEntityName: "Notification", in: managedObjectContext)
        let notification = NSManagedObject(entity: entity!, insertInto: managedObjectContext)
        
        notification.setValue(date, forKey: "id")
        notification.setValue(title, forKey: "title")
        notification.setValue(body, forKey: "body")
        
        do {
            try managedObjectContext.save()
        } catch  {
            fatalError("无法保存")
        }
        
        notifications.append(notification)
    }
    

猜你喜欢

转载自blog.csdn.net/PrecipitantPan/article/details/81252242
今日推荐