zoukankan      html  css  js  c++  java
  • Core Data的简单实用

    1. 新建数据库

       1.1 在新项目中

           创建时勾选 Use Core Data即可,XCode会帮我们创建一个,

           且在AppDelegate文件中生成获取context方法和保存的方法

       2.1 在旧项目中

           New File -> Core Data -> Core Model

    2. 新建表

       选中数据库文件xx.xcdatamodelId

       点击左下角的AddEntity, 在左上角中出现Default的表,更改为自己想要的名字即可

       Attributes 中可以添加属性名和属性类型

       Relationships 中可以添加关系(给第一个表添加关系时 Inverse的选项只有‘Inverse’,需要给第二个关联表也加上关系),在右栏Data Inspectable的Type中选择(To One’ or ‘To Many’ )

    4. 升级数据库

       选中数据库文件xx.xcdatamodelId

       点击菜单Editor -> Add Model Version... -> 写入数据的名字

       在右栏Fiel Inspectable的Core Data Model -> Model Version -> Current 中选中新的数据库名即可

       

    5. 增删改查

    class GLCoreDataManager: NSObject {
    
        static let shared: GLCoreDataManager = GLCoreDataManager()
        
        //xcdatamodel 的name
        public var dbName: String = "Model"
        
        
        // 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: self.dbName)
            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)")
                }
            }
        }
        
        /// 添加一条实体数据
        /// - Parameters:
        ///   - entityName: 实体名称
        ///   - completion: 在闭包中做属性的填充
        func addData(with entityName: String, completion: (NSManagedObject)->Void) {
            let context = self.persistentContainer.viewContext
            
            let model = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context)
            completion(model)
            saveContext()
        }
        
        
        /// 创建一条实体数据
        /// - Parameter entityName: 实体名称
        /// - Returns: NSManagedObject实例
        func createData(with entityName: String) -> NSManagedObject {
            let context = self.persistentContainer.viewContext
            
            let model = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context)
            return model
        }
        
        /// 根据条件删除相应的实体数据
        /// - Parameters:
        ///   - entityName: 实体名称
        ///   - predicate: 谓词正则(String)
        func deleteData(with entityName: String, predicate: String) {
            let predicate2 = NSPredicate(format: predicate, "")
            deleteData(with: entityName, predicate: predicate2)
            addData(with: "") { ent in
                
            }
        }
        
        /// 根据条件删除相应的实体数据
        /// - Parameters:
        ///   - entityName: 实体名称
        ///   - predicate: 谓词正则(NSPredicate)
        func deleteData(with entityName: String, predicate: NSPredicate? = nil) {
            let context = self.persistentContainer.viewContext
            let m = self.fetchData(with: entityName, limit: Int.max, offset: 0, predicate: predicate) as? [NSManagedObject]
            guard let array = m else { return }
            for info in array {
                context.delete(info)
            }
            saveContext()
        }
        
        /// 获取相应条件下的所有数据列表
        /// - Parameters:
        ///   - entityName: 实体名称
        ///   - limit: 每页的大小
        ///   - offset: 页码的偏移量
        ///   - predicate: 谓词正则(String)
        /// - Returns: 模型列表
        func fetchData(with entityName: String, limit: Int = 20, offset: Int = 0, predicate: String) -> [Any]?{
            let predicate2 = NSPredicate(format: predicate, "")
            return self.fetchData(with: entityName, limit: limit, offset: offset, predicate: predicate2)
        }
        
        
        /// 获取相应条件下的所有数据列表
        /// - Parameters:
        ///   - entityName: 实体名称
        ///   - limit: 每页的大小
        ///   - offset: 页码的偏移量
        ///   - predicate: 谓词正则(NSPredicate)
        /// - Returns: 模型列表
        func fetchData(with entityName: String, limit: Int = 20, offset: Int = 0, predicate: NSPredicate? = nil) -> [Any]? {
            let context = self.persistentContainer.viewContext
            let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
            request.fetchOffset = offset
            request.fetchLimit = limit
            if let p = predicate {
                request.predicate = p
            }
            do {
                let fetchObjects = try context.fetch(request)
                return fetchObjects
            } catch {
                return nil
            }
        }
        
        /// 获取相应条件下的第一条数据列表
        /// - Parameters:
        ///   - entityName: 实体名称
        ///   - predicate: 谓词正则(NSPredicate)
        /// - Returns: 第一条数据对象
        func fetchOne(with entityName: String, predicate: NSPredicate? = nil) -> Any? {
            return self.fetchData(with: entityName, limit: 1, offset: 0, predicate: predicate)?.first
        }
        
        
        /// 获取相应条件下的第一条数据列表
        /// - Parameters:
        ///   - entityName: 实体名称
        ///   - predicate: 谓词正则(String)
        /// - Returns: 第一条数据对象
        func fetchOne(with entityName: String, predicate: String) -> Any? {
            return self.fetchData(with: entityName, limit: 1, offset: 0, predicate: predicate)?.first
        }
        
        /// 修改数据
        /// - Parameters:
        ///   - entityName: 实体名称
        ///   - predicate: 谓词正则(NSPredicate)
        ///   - completion: 在闭包中做相应的修改
        func modifyData(with entityName: String, predicate: NSPredicate? = nil, completion: (NSManagedObject)->Void) {
            let m = self.fetchData(with: entityName, limit: Int.max, offset: 0, predicate: predicate) as? [NSManagedObject]
            guard let array = m else { return }
            for info in array {
                completion(info)
            }
            saveContext()
        }
        
        /// 修改数据
        /// - Parameters:
        ///   - entityName: 实体名称
        ///   - predicate: 谓词正则(String)
        ///   - completion: 在闭包中做相应的修改
        func modifyData(with entityName: String, predicate: String, completion: (NSManagedObject)->Void) {
            let predicate2 = NSPredicate(format: predicate, "")
            modifyData(with: entityName, predicate: predicate2, completion: completion)
        }
        
    }
    

    6. 地址

       Apple    Github

  • 相关阅读:
    有关TensorBoard一些小Tip和实例
    基于Word2Vec的影评挖掘
    CNN实战2:CIFAR-10数据集上的图像识别
    CNN实战1:实现模仿大师绘画
    delphi
    表格录入控件
    税控接口
    TStringGrid
    TStringGrid
    sqlserver
  • 原文地址:https://www.cnblogs.com/gulong/p/15162042.html
Copyright © 2011-2022 走看看