iOS数据存储除了SQLite,FMDB,归档之外,项目中涉及最多的就是CoreData.CoreData底层数据存储也是SQLite,作为苹果官方支持的类似ORM的框架,相对于直接操作SQLite而言,CoreData至少减少了60%~80%的代码量.
CoreData相比SQLite更加面向对象,对于一些数据查询,更新,建表等过程不必要过于关心,关注重点在Model层面.CoreData相比其他数据库的优势:
① 对象一致性,Model改变之后全局统一,保持对象关系之间的一致性.
② 属性的自动验证,CoreData中实体对象,可以设置插入规则,使属性值在可接受的范围.
③ 实体对象懒加载,CoreData中的关联对象,并不是在获取实体的时候就从数据库加载至内存中,而是在使用过程中才从数据中进行加载.
④ 版本迁移,相对于SQLite而言,CoreData实现版本迁移的方式简单高效.
⑤ 复杂查询,对于复杂的SQL语句,可以通过NSPredicate读取对象的复杂查询.
基础知识
项目中如果起始就需要使用CoreData,建立的时候可以勾选Use Core Data选项:
如果第一次没有漏掉了Core Data选项,或者项目中途需要使用CoreData,创建新的Data Model即可.
创建的对象模型类型是NSManagedObjectModel托管类型的,一个托管对象模型关联一个模型文件(.xcdatamodeld),存储着数据库的数据结构.
创建实体对象Order,添加订单号和订单名称两个属性:
可以创建Order的对象,创建步骤如下:
选择需要创建的实体对象:
所有创建的实体对象都是NSManagedObject的子类,对象CoreData中的Entity.
如果我们想对Order表进行常规则查询,更新,删除操作,会涉及到两个重要的类NSManagedObjectContext对象上下文,NSPersistentStoreCoordinator持久化协调器,负责Context和存储之间的关系.实际执行过程如下:
增删改查
添加100条的订单数据:
for i in 1...100 {
let context:NSManagedObjectContext = CoreDataManager.sharedManager.mainQueueContext
let order:Order = NSEntityDescription.insertNewObject(forEntityName: "Order", into: context) as! Order
order.orderName = "台湾小零食--\(i)"
order.orderNumber = Int32(i)
if context.hasChanges {
do {
print("保存成功")
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
查询插入的数据:
Order.findAllOrders()
Order表中查询本地所有数据:
static func findAllOrders() {
let context:NSManagedObjectContext = CoreDataManager.sharedManager.mainQueueContext
let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Order")
let sortDescriptor = NSSortDescriptor.init(key: "orderNumber", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
do {
let searchResults = try context.fetch(fetchRequest)
if searchResults.count > 0 {
for i in 0..
数据更新,根据订单标号更新对应的数据:
let number:Int = 30
let order:Order? = Order.findOrderByID(id: number)
if order != nil {
print("订单号:\(number)的订单名称:\(order?.orderName)")
order?.orderName = "FlyElephant\(number)_update"
let context:NSManagedObjectContext = CoreDataManager.sharedManager.mainQueueContext
if context.hasChanges {
do {
print("FlyElephant更新成功")
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
Order中根据OrderNumber获取对应的Order数据:
static func findOrderByID(id:Int) -> Order? {
let context:NSManagedObjectContext = CoreDataManager.sharedManager.mainQueueContext
let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Order")
let predicate = NSPredicate.init(format: " orderNumber = %@", "\(id)")
fetchRequest.predicate = predicate
do {
let searchResults = try context.fetch(fetchRequest)
if searchResults.count > 0 {
let order:Order = searchResults[0] as! Order
return order
} else {
return nil
}
} catch {
print(error)
}
return nil
}
更新之后,执行查询操作,显示如下:
根据orderNumer查询order,删除对应的订单:
let number:Int = 80
let order:Order? = Order.findOrderByID(id: number)
if order != nil {
print("FlyElephant订单号:\(number)的订单名称:\(order?.orderName)")
let context:NSManagedObjectContext = CoreDataManager.sharedManager.mainQueueContext
context.delete(order!)
if context.hasChanges {
do {
print("\(number)删除成功")
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
CoreDataManager是对CoreData的基本封装,代码如下:
class CoreDataManager {
// MARK: 初始化
static let sharedManager = CoreDataManager()
static let applicationDocumentsDirectoryName = "com.coredata.www"
static let mainStoreFileName = "FECoreData.sqlite"
static let errorDomain = "CoreDataManager"
lazy var managedObjectModel: NSManagedObjectModel = {
// 对应存储的模型FECoreData.xcdatamodeld
let modelURL = Bundle.main.url(forResource: "FECoreData", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
// 持久化协调器
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
do {
// 自动升级选项设置
let options = [
NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true
]
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: self.storeURL as URL, options: options)
}
catch {
fatalError("FlyElephant持久化存储错误: \(error).")
}
return persistentStoreCoordinator
}()
lazy var mainQueueContext: NSManagedObjectContext = {
let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
moc.persistentStoreCoordinator = self.persistentStoreCoordinator
// 避免多线程中出现问题,如果有属性和内存中都发生了改变,以内存中的改变为主
moc.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
return moc
}()
/// CoreData 文件存储目录
//
lazy var applicationSupportDirectory: URL = {
let fileManager = FileManager.default
var supportDirectory:URL = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).last!
var saveUrl:URL = supportDirectory.appendingPathComponent(applicationDocumentsDirectoryName)
if fileManager.fileExists(atPath: saveUrl.path) == false {
let path = saveUrl.path
print("文件存储路径:\(path)")
do {
try fileManager.createDirectory(atPath: path, withIntermediateDirectories:true, attributes:nil)
}
catch {
fatalError("FlyElephant文件存储目录创建失败: \(path).")
}
}
return saveUrl
}()
lazy var storeURL: URL = {
return self.applicationSupportDirectory.appendingPathComponent(mainStoreFileName)
}()
// 创建私有CoreData存储线程
func newPrivateQueueContextWithNewPSC() throws -> NSManagedObjectContext {
// 子线程中创建新的持久化协调器
//
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: CoreDataManager.sharedManager.managedObjectModel)
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: CoreDataManager.sharedManager.storeURL as URL, options: nil)
let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
context.performAndWait() {
context.persistentStoreCoordinator = coordinator
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
}
return context
}
}