swift - 核心数据 : Setting the Related Object Takes Too Long

标签 swift xcode performance core-data

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 ,所以当我涉及另一个 productinvoiceLine它将再次加载所有相关的 invoiceLine对于那个特定的 product ,最终内存分配变得越来越大。

问题:是否可以阻止coredata加载所有相关的invoiceLine对于 product当我这样做时:invoiceLine.product = product

最佳答案

我不知道这是否是一个好习惯,但我设法通过切断 productinvoiceline 的反向关系来减少执行时间:

invoiceLine ----> 产品

这一次,CoreData 没有理由为我不需要的特定 product 加载所有相关的 invoiceline,从而提高了性能。

关于swift - 核心数据 : Setting the Related Object Takes Too Long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41993402/

相关文章:

dictionary - 如何将值插入嵌套 Swift 字典

iOS/swift 3 : Passing data backwards between non consecutive View Controllers

java - 在 Java 中删除字符串中第一个单词的最佳方法

ios - 如何避免此处搜索栏和表格 View 之间的额外间隙并在它们之间放置分隔符?

python - numpy 与 native Python - 最有效的方式

performance - 多用户情况下重新链接数据库缓慢

ios - 二元运算符 '!=' 不能应用于类型 "UIImage"的操作数

ios - Alamofire 在范围之外返回值 - 该代码如何工作?

Xcode 在准备存档时花费太多时间来编译位代码

ios - 导航和标签栏 Controller 未显示