首页 > 代码库 > 【Swift学习笔记-《PRODUCT》读书记录-CoreData数据存储】

【Swift学习笔记-《PRODUCT》读书记录-CoreData数据存储】

《PRODUCT》中小记记录的文字信息,都是使用CoreData存储在本地的。下面将详细介绍,如何在xcode8中使用CoreData。

首先新建一个数据模型文件Diary.Xcatamodeld文件,如图:

技术分享

选中这个数据库文件,右边可以给这个表增加属性字段

技术分享

完成后,选中该文件,点击Editor菜单中的,“Ctreate NSManageObject Subclass”导出生成NSManagedObject

技术分享

然后再对数据库文件做初始化,在appdelegate中创建managedObjectModel

  lazy var managedObjectModel: NSManagedObjectModel = {
        // 描述数据模型描述文件存储位置
        let modelURL = Bundle.main.url(forResource: "DiaryText", withExtension: "momd")!
        return NSManagedObjectModel(contentsOf: modelURL)!
    }()

 创建persitentStoreCoordinator持久化管理

 

  lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
        // 通过 managedObjectModel 创建持久化管理
        var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel:self.managedObjectModel)
        
        let url = self.applicationDocumentsDirectory.appendingPathComponent("DiaryText2.sqlite")
        // 设定数据库存储位置
        
        var error: NSError? = nil
        var failureReason = "载入程序存储的数据出错."
        
        do {
            try coordinator!.addPersistentStore(
                ofType: NSSQLiteStoreType, configurationName: nil,
                at: url, options: nil)
            // 创建NSSQLiteStoreType类型持久化存储
        } catch var error1 as NSError {
            error = error1
            coordinator = nil
            // 报告错误
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "无法初始化程序存储的数据" as AnyObject?
            dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
            dict[NSUnderlyingErrorKey] = error
            error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
            NSLog("发现错误 \(error), \(error!.userInfo)")
            abort()
        } catch {
            fatalError()
        }
        
        return coordinator
    }()

 创建managedObjectContext数据库上下文:

lazy var managedObjectContext: NSManagedObjectContext? = {
        let coordinator = self.persistentStoreCoordinator
        if coordinator == nil {
            return nil
        }
        var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = coordinator
        return managedObjectContext
    }()

 因为后续会项目中会时常使用上下文,所以在appdelegate中定义了一个常量

// Coredata
let appDelegate = UIApplication.shared.delegate as! AppDelegate

let managedContext = appDelegate.managedObjectContext!

 到这里数据库基本初始化完成。接下来就是保存数据了,点击完成按钮保存数据

func ednBtnClick() { // 保存数据
        self.titleView.endEditing(true)
        self.contentView.endEditing(true)
        if contentView.text.lengthOfBytes(using: String.Encoding.utf8) > 0 {
            let entity =  NSEntityDescription.entity(forEntityName: "DiaryText", in: managedContext)
            
            let newdiary = DiaryText(entity: entity!,
                                 insertInto:managedContext)
            newdiary.context = contentView.text
            newdiary.location = "123"
            if titleView.text.lengthOfBytes(using: String.Encoding.utf8) > 0 {
                newdiary.title = titleView.text
            }
            var error:NSError?
            do{
                try managedContext.save()
       
            }catch let error1 as NSError{
                error = error1
                print("保存出错\(error),\(error?.userInfo)")
            }
            
           
        }
        
         self.navigationController?.popToRootViewController(animated: true)
    }

还可以自行在diary数据库文件中扩展方法。

接下来介绍怎么从CoreData中查询想要的信息。

  // 查询数据
        
        do {
            // 新建查询
            let fetchRequest = NSFetchRequest<DiaryText>(entityName:"DiaryText")
            
            // 排序方式
            fetchRequest.sortDescriptors = [NSSortDescriptor(key: "created_at", ascending: true)]
            
            // 排序方式
            fetchRequest.sortDescriptors = [NSSortDescriptor(key: "context", ascending: true)]
            
            fetched = NSFetchedResultsController(fetchRequest: fetchRequest,
                                                                  managedObjectContext: managedContext, sectionNameKeyPath: "year",
                                                                  cacheName: nil)
            
            // 建立委托关系
//            fetchedResultsController.delegate = self
            
            // 尝试查询
            try self.fetched.performFetch()
            
            
            if (fetched.fetchedObjects!.count == 0){
                print("没有存储结果")
            }else{
                if let sectionsCount = fetched.sections?.count {
                    yearsCount = sectionsCount
                    diartys = fetched.fetchedObjects!
                }else{
                   yearsCount = 1
                   sectionsCount = 0
                }
                
            }
            
        } catch let error as NSError {
            NSLog("发现错误 \(error.localizedDescription)")
        }
        for obj in diartys{
            print("\(obj.context),,,\(obj.title)")
//            managedContext.delete(obj)
        }

    }

 以上便是CoreData使用介绍

【Swift学习笔记-《PRODUCT》读书记录-CoreData数据存储】