gpt4 book ai didi

swift - saveWithBlock 方法中的 MagicalRecord 未找到具有 MR_FindFirstByAttribute 的现有实体 - Swift

转载 作者:行者123 更新时间:2023-11-30 14:19:44 24 4
gpt4 key购买 nike

我正在尝试使用此 block 导入实体

 MagicalRecord.saveWithBlock({   (moc: NSManagedObjectContext!) in                

//parsing inquiries
for (index: String, jsonInquiry: JSON) in json["data"]["inquiries"] {

var idInquiry = jsonInquiry["id_inquiry"].int!
var inquiry: Inquiry

//trying to find existing entity
if let existingInquiry = Inquiry.MR_findFirstByAttribute("id", withValue: idInquiry, inContext: moc) as? Inquiry {
inquiry = existingInquiry
println("fetching existing inquiry: \(idInquiry)")
} else {
inquiry = Inquiry.MR_createInContext(moc) as! Inquiry
println("creating new inquiry: \(idInquiry)")
}
...
}
}

Only first entity is found as existing, others are created as new

但是当我使用以下命令一次性预取所有实体时:

 MagicalRecord.saveWithBlock({  (moc: NSManagedObjectContext!) in

//preFetch all entities
var existingInquiries = [Int:Inquiry]()
for item in Inquiry.MR_findAllInContext(moc) {
if let existingItem = item as? Inquiry {
existingInquiries[ existingItem.id ] = existingItem
}
}

//parsing inquiries
for (index: String, jsonInquiry: JSON) in json["data"]["inquiries"] {
....
var idInquiry = jsonInquiry["id_inquiry"].int!
var inquiry: Inquiry

if let existingInquiry = existingInquiries[idInquiry] {
inquiry = existingInquiry
println("fetching existing inquiry: \(idInquiry)")
} else {
inquiry = Inquiry.MR_createInContext(moc) as! Inquiry
println("fetching new inquiry: \(idInquiry)")
}
}
....
}

all entities are found as existing

有人可以发现我的错误或错误吗?也许我缺少一些基本的东西。我为此苦苦挣扎了几个小时

谢谢

我使用 XCODE 版本 6.3 (6D570) 和 Swift 1.2

最佳答案

我发现我的错误了a 在我的循环中包含此代码 - 它应该是上一级:)

for inquiry in existingInquiries.values {
if !contains(importedInquiries, inquiry) {
inquiry.MR_deleteInContext(moc)
}
}

关于swift - saveWithBlock 方法中的 MagicalRecord 未找到具有 MR_FindFirstByAttribute 的现有实体 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30623847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com