想要實現(xiàn)可視化建模扇谣,需要New File,選擇Core Data>Data Model闲昭,建立模型罐寨,模型名稱,最好與工程名相同
一序矩、對象與實體的映射
對象(Object)與數(shù)據(jù)庫的實體(Entity)對應
對象與實體都擁有屬性(Attribute)
CoreData.png
@圖片是二進制文件
二鸯绿、創(chuàng)建托管對象
一旦使用CoreData,必須要把對象置于CoreData框架托管
在當前創(chuàng)建的可視化模型中簸淀,在其屬性的Class > Name,加上MO瓶蝴,這樣,在Build工程后租幕,會自動創(chuàng)建name+MO的托管對象 的類定義舷手,但文件是不可見的
//由于此時 不需要再沒次都用代碼寫數(shù)據(jù),數(shù)據(jù)源可以留空
var areas : [AreaMO] = []
三令蛉、保存數(shù)據(jù)的步驟
iOS10中大幅度簡化了Core Data用法聚霜,保存數(shù)據(jù)只需要2步
3.1狡恬、類似一下代碼,創(chuàng)建一個AreaMO實例蝎宇,設置屬性
var area: AreaMO!
3.2弟劲、調(diào)用AppDelegate中的saveContext方法
@IBAction func saveTap(_ sender: UIBarButtonItem) {
//獲取appDelegate
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//Core Data持久化容器中的context
area = AreaMO(context: appDelegate.persistentContainer.viewContext)
area.name = tfName.text
area.province = tfProvince.text
area.part = tfPart.text
area.visited = isVisited
//圖片轉為 JPG格式
if let imageData = UIImageJPEGRepresentation(coverImageView.image!, 0.7) {
area.thumbImage = NSData(data: imageData) as Data
}
//保存并返回首頁
print("正在保存")
appDelegate.saveContext()
performSegue(withIdentifier: "unwindToHomeList", sender: self)
}
四、讀取保存的數(shù)據(jù)
// MARK: - 寫一個獲取所有Area Entity下數(shù)據(jù)的方法
func fetchAllData() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//do-try-catch錯誤處理
do {
//AreaMO.fetchRequest() 獲取AreaMO此Entity的所有條目
areas = try appDelegate.persistentContainer.viewContext.fetch(AreaMO.fetchRequest())
} catch {
print(error)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
//放在viewDidAppear里執(zhí)行
fetchAllData()
tableView.reloadData()
}
五姥芥、高效刷新:
沒次全部更新tableView兔乞,性能上是不可接受的
能達到以下效果再好不過
加一條,出現(xiàn)一條
刪一條凉唐,少一條
NSFetchedResultsController
可把單元格內(nèi)容與數(shù)據(jù)進行綁定庸追,響應數(shù)據(jù)變化
@第一步:
import CoreData
@第二步:
遵從NSFetchedResultsControllerDelegate協(xié)議
此協(xié)議提供數(shù)據(jù)變化時的通知及代理的方法
@第三步:
定義一個NSFetchedResultsController變量
var fc : NSFetchedResultsController<AreaMO>!
@主體代碼:
func fetchAllData2() {
//請求結果是AreaMO
let request : NSFetchRequest<AreaMO> = AreaMO.fetchRequest()
//NSSortDescriptor指定請求結果如何排序
let sd = NSSortDescriptor(key: "name", ascending: true)
request.sortDescriptors = [sd]
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
//NSFetchedResultsController初始化后,指定代理
fc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
fc.delegate = self
//執(zhí)行查詢台囱,將結果保存到數(shù)組中
do {
try fc.performFetch()
if let objects = fc.fetchedObjects {
areas = objects
}
} catch {
print(error)
}
//如果執(zhí)行淡溯,會顯示上一次保存的數(shù)據(jù),但新增數(shù)據(jù)后簿训,表格不會更新
}
六咱娶、代理方法
當數(shù)據(jù)內(nèi)容發(fā)生變化時,NSFetchedResultsControllerDelegate協(xié)議的以下方法會被調(diào)用:
//當控制器開始處理內(nèi)容變化時
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
//內(nèi)容發(fā)生變更時
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .delete:
tableView.deleteRows(at: [indexPath!], with: .automatic)
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .automatic)
case .update:
tableView.reloadRows(at: [indexPath!], with: .automatic)
default:
tableView.reloadData()
}
if let objects = controller.fetchedObjects {
areas = objects as! [AreaMO]
}
}
//當控制器已經(jīng)處理完內(nèi)容變更時
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
七强品、真正的刪除
@修改之前tableView的刪除方法
self.areas.remove(at: indexPath.row)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.delete(self.fc.object(at: indexPath))
appDelegate.saveContext()
// 此處需要注釋掉膘侮,因為我們已經(jīng)控制了數(shù)據(jù)庫的刪除
// tableView.deleteRows(at: [indexPath], with: .fade)
@然后更新對象
reviewVC.ratingCloser = { (value:String) -> Void in
self.area.rating = value
self.RatingBtn.setImage(UIImage(named: value), for: .normal)
}
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.saveContext()
@重新讀取
if let rating = area.rating {
self.RatingBtn.setImage(UIImage(named: rating), for: .normal)
}