【Swift學習筆記-《PRODUCT》讀書記錄-CoreData數據存儲】

《PRODUCT》中小記記錄的文字信息,都是使用CoreData存儲在本地的。下面將詳細介紹,如何在xcode8中使用CoreData。sql

首先新建一個數據模型文件Diary.Xcatamodeld文件,如圖:數據庫

選中這個數據庫文件,右邊能夠給這個表增長屬性字段xcode

完成後,選中該文件,點擊Editor菜單中的,「Ctreate NSManageObject Subclass」導出生成NSManagedObjectapp

而後再對數據庫文件作初始化,在appdelegate中建立managedObjectModeldom

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

 建立persitentStoreCoordinator持久化管理fetch

 

  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數據庫上下文:url

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

 由於後續會項目中會時常使用上下文,因此在appdelegate中定義了一個常量3d

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

let managedContext = appDelegate.managedObjectContext!

 到這裏數據庫基本初始化完成。接下來就是保存數據了,點擊完成按鈕保存數據code

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數據庫文件中擴展方法。orm

接下來介紹怎麼從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使用介紹

相關文章
相關標籤/搜索