CoreData 实体结构:
Invoice <---->> Invoiceline <<-----> Product
NSManaged对象类实现
// intended to be overridden by the subclass
class var entityName { /* return the entity name */ }
// generic class function to create new entity
class func create() -> NSManagedObject
{
let context = // the main context
let record = NSEntityDescription.insertNewObjectForEntityForName(self.entityName, inManagedObjectContext: context)
return record
}
示例交易:
let product = // a product object
let invoice = Invoice.create() as! Invoice
let invoiceLine = InvoiceLine.create() as! InvoiceLine
invoiceLine.product = product
invoiceLine.invoice = invoice
// complete the transaction
invoice.checktout()
当核心数据中插入的发票数量达到200K时,设置invoiceLine's
product
属性花费的时间太长:
invoiceLine.product = product
所以,我使用 XCode 工具来检查内存分配,我发现,每次我 invoiceLine.product = product
, coredata 正在加载所有相关的 invoiceLines
对于 product
,在我的例子中是 6K 的 invoiceLines
,所以当我涉及另一个 product
至 invoiceLine
它将再次加载所有相关的 invoiceLine
对于那个特定的 product
,最终内存分配变得越来越大。
问题:是否可以阻止coredata加载所有相关的invoiceLine
对于 product
当我这样做时:invoiceLine.product = product
?
最佳答案
我不知道这是否是一个好习惯,但我设法通过切断 product
与 invoiceline
的反向关系来减少执行时间:
invoiceLine ----> 产品
这一次,CoreData 没有理由为我不需要的特定 product
加载所有相关的 invoiceline
,从而提高了性能。
关于swift - 核心数据 : Setting the Related Object Takes Too Long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41993402/