gpt4 book ai didi

swift - 创建新的 NSManagedObject 并将其分配给新的 NSManagedObject *有时*会失败

转载 作者:行者123 更新时间:2023-11-30 10:07:17 25 4
gpt4 key购买 nike

我正在创建一个名为“translation”的新 NSManagedObject。在翻译中,我需要创建两个额外的 NSManagedObjects 称为“phrase”。有时,其中一个短语分配会引发错误,但当我检查这些值时,它们看起来都创建得很好。什么给了???

error when adding a phrase to a translation

threads

创建翻译对象:

func getOrCreateTranslation(package: Package?, data: NSDictionary) -> Translation {
let translationId = data["id"] as! NSNumber

if let translation = self.getTranslation(translationId) {

return translation

} else {

let context = LocalDataStorage().context
let translation = NSEntityDescription.insertNewObjectForEntityForName("Translation", inManagedObjectContext: context) as! Translation
translation.id = translationId

let fromPhrase = data["from_phrase"]! as! NSDictionary
let toPhrase = data["to_phrase"]! as! NSDictionary


let pm = PhraseManager()

//*******
// *SOMETIMES* ONE OF THESE LINES FAIL WITH BAD_EXC_ACCESS code=1
translation.fromPhrase = pm.getOrCreatePhrase(fromPhrase)
translation.toPhrase = pm.getOrCreatePhrase(toPhrase)
//******

if package != nil {
package!.addTranslationObject(translation)
}

return translation

}

}

创建短语对象:

func getOrCreatePhrase(data: NSDictionary) -> Phrase {
// check if phrase exists
let phraseId = data["id"] as! NSNumber

if let phrase = self.getPhrase(phraseId) {

return phrase

} else {

let context = localDataStorage.context
let lm = LanguageManager()
let phrase = NSEntityDescription.insertNewObjectForEntityForName("Phrase", inManagedObjectContext: context) as! Phrase

phrase.id = phraseId
phrase.text = data["text"] as! String
phrase.audioUrl = data["audio_url"] as? String

let code = data["language"]!["language_code"] as! String
phrase.language = lm.getLanguageFromCode(code)

return phrase

}



}

对 API 进行调用:

func getPackageTranslations(package: Package, completion: ([Translation])-> Void) {

let currentLanguage: Language = LanguageManager().getCurrentLanguage()!

let urlString = baseAPIString + "/groups/\(package.id!)/translations/?language_code=\(currentLanguage.code)"


let session = NSURLSession.sharedSession()
let serachUrl = NSURL(string: urlString)


let task = session.dataTaskWithURL(serachUrl!) {
(data, response, error) -> Void in

if error != nil {
print(error?.localizedDescription)
} else {



let jsonData: NSDictionary!
do {
jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary
} catch _ {
jsonData = NSDictionary()
}

let groupTranslationsData = jsonData["group_translations"] as! [NSDictionary]



var translations = [Translation]()
let context = LocalDataStorage().context

for groupTranslation in groupTranslationsData {

let translationData = groupTranslation["translation"] as! NSDictionary

let translation = TranslationManager().getOrCreateTranslation(package, data: translationData)


if translation.packages?.containsObject(package) == false {
//package.addTranslationObject(translation!)
//translation!.addPackageObject(package)
}

translations.append(translation)

}


do {
try context.save()
} catch {
print("There was a problem saving translation ")
}




dispatch_async(dispatch_get_main_queue(), {
completion(translations)
})


}

}
task.resume()

}

CoreData 上下文类:

    class LocalDataStorage {
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext!

init() {
context = appDelegate.managedObjectContext
}

}

最佳答案

当您创建一个具有应与之交互的并发模式的 NSManagedObjectContext,并且您在与初始化期间指定的并发模式不同的线程上对其执行操作时,就会出现此问题。

NSURLSession.dataTaskWithURL 的完成 block 在另一个线程上运行,因此您必须分派(dispatch)到上下文创建中指定的线程类型才能在其上成功执行任何操作。

如果您的上下文并发类型是大多数情况下使用的MainQueueConcurrencyType,则必须在主队列上执行上下文保存方法。

dispatch_async(dispatch_get_main_queue()) {
do {
try context.save()
} catch {
print("There was a problem saving translation ")
}
completion(translations)
}

关于swift - 创建新的 NSManagedObject 并将其分配给新的 NSManagedObject *有时*会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35351743/

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