CoreData实现基础的增删改查其实非常简单,作为实际开发你可能还需要了解CoreData版本迁移,CoreData实体对象之间的关联关系,Context上下文实际操作过程中常见的误操作,NSManagedObjectID的用途.简单归类于高阶,其实只是一些CoreData常用但易错的知识点.
版本迁移
项目中开发根据业务的发展,新增不同的表,也会对原有的表进行扩充,修改实体对象的同时,我们需要对Model(.xcdatamodeld文件)进行升级,避免用户在升级的时候发生崩溃.
① 新增版本号:
版本名字根据个人喜好和项目来命名
② 版本号新增之后在Model下可以看到新增的版本
③ 设置当前版本号为最新的版本号
④NSMigratePersistentStoresAutomaticallyOption设置为true表示CoreData会试着将低版本的持久化存储区迁移到最新版本的模型文件,NSInferMappingModelAutomaticallyOption设置为true表示CoreData会试着以最为合理地方式自动推断出源模型文件的实体中,某个属性到底对应于目标模型文件实体中的哪一个属性.
// 自动升级选项设置
let options = [
NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true
]
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: self.storeURL as URL, options: options)
关联关系
CoreData中实体关联关系有三种,一对一,一对多,多对多,举一个简单的例子Accoun和Order之间关系.一个账户有多个订单.
图中的RelationShip有三个字段,关联关系的名称,对应的Destination目标表的名字,Inverse表示反向关系,如果没有就是No Inverse.苹果关系建议是为了保证数据之间的一致性,最好设置反向关系.每个Order对应单一的用户.
设置关联之后还需要设置对应的删除规则(Delete Rule),苹果默认的关联规则是Nullify:
Deny 关系的Destination中只要有一个对象,就不能删除,如果账户还有订单,就不能删除账户
Nullify 只在逆向关系Optional的时候有效,Accout 删除之后,所有的Order中的account信息设置为nil
Cascade 删除对象后,删除destination所有对象.Account删除之后,会删除所有对应的Order对象.
NoAction 删除对象后,对Destination不做任何操作,在Destination中有大量对象的时候有用.
Context上下文
NSManagedObjectContext是连接对象和数据存储之间的桥梁,Context有两种并发类型,主线程和子线程并发类型.
public enum NSManagedObjectContextConcurrencyType : UInt {
@available(iOS, introduced: 3.0, deprecated: 9.0, message: "Use another NSManagedObjectContextConcurrencyType")
case confinementConcurrencyType
case privateQueueConcurrencyType
case mainQueueConcurrencyType
}
① 如果Context是nil,会遇到以下错误:
+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name ‘Account’’
数据操作的时候尽量保证Context不为空.
② 设置关联关系,新建立一个订单,设置Order的关联对象是Account:
do {
let account:Account = Account.findAccountByName(name: "FlyElephant")!
let privateContext:NSManagedObjectContext = try CoreDataManager.sharedManager.newPrivateQueueContextWithNewPSC()
let order:Order = NSEntityDescription.insertNewObject(forEntityName: "Order", into: privateContext) as! Order
order.orderName = "台湾小零食--\(1)"
order.orderNumber = Int32(100)
order.account = account
if privateContext.hasChanges {
do {
print("保存成功")
try privateContext.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
} catch {
print(error)
}
Account查询:
static func findAccountByName(name:String) -> Account? {
let context:NSManagedObjectContext = CoreDataManager.sharedManager.mainQueueContext
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Account")
let predicate = NSPredicate.init(format: " accountName = %@", name)
fetchRequest.predicate = predicate
do {
let searchResults = try context.fetch(fetchRequest)
if searchResults.count > 0 {
let account:Account = searchResults[0] as! Account
return account
} else {
return nil
}
} catch {
print(error)
}
return nil
}
但是这个时候会报错:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'account' between objects in different contexts (source = <Order: 0x600000090ef0> (entity: Order; id: 0x60000022ffa0 <x-coredata:///Order/t0026FC90-22DC-459F-B59F-D0A225505AFE3> ; data: {
account = nil;
orderName = "\U53f0\U6e7e\U5c0f\U96f6\U98df--1";
orderNumber = 100;
}) , destination = <Account: 0x600000090310> (entity: Account; id: 0xd000000000040000 <x-coredata://D472E515-79B3-469F-A842-73AE3A38D9F8/Account/p1> ; data: <fault>))'
Account和Order不在同一个Context上下文中,所以会出现错误,可以在同一个上下文中进行实体对象查询:
do {
let account:Account = Account.findAccountByName(name: "FlyElephant")!
let privateContext:NSManagedObjectContext = try CoreDataManager.sharedManager.newPrivateQueueContextWithNewPSC()
let order:Order = NSEntityDescription.insertNewObject(forEntityName: "Order", into: privateContext) as! Order
order.orderName = "FlyElephant-台湾小零食--\(1)"
order.orderNumber = Int32(100)
let accountInContext:Account = privateContext.object(with: account.objectID) as! Account
order.account = accountInContext
if privateContext.hasChanges {
do {
print("保存成功")
try privateContext.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
} catch {
print(error)
}
其中的objectID类型是NSManagedObjectID,并不是字符串类型:
open class NSManagedObjectID : NSObject, NSCopying {
open var entity: NSEntityDescription { get } // entity for the object identified by an ID
weak open var persistentStore: NSPersistentStore? { get } // persistent store that fetched the object identified by an ID
open var isTemporaryID: Bool { get } // indicates whether or not this ID will be replaced later, such as after a save operation (temporary IDs are assigned to newly inserted objects and replaced with permanent IDs when an object is written to a persistent store); most IDs return NO
open func uriRepresentation() -> URL // URI which provides an archivable reference to the object which this ID refers
}`</code></pre>