gpt4 book ai didi

swift - 使用 Swift 2.0 处理 CoreData 中的顺序错误的最佳实践

转载 作者:行者123 更新时间:2023-11-30 14:05:15 25 4
gpt4 key购买 nike

假设我做了这样的事情:

do {
try context.executeFetchRequest(..)
// tweak the results
// build a relation
try context.save()
} catch { ... }

最好是为 context.save() 的调用执行第二个 do block ,还是按照上面所示的顺序执行所有 try 调用?

不过,如果我想以不同的方式处理任何潜在的错误,最好将它们作为嵌套的 do block 来执行。同样,如果您想以相同的方式处理任何错误,则应该连续执行它们。

最佳答案

我的观点是,获取关系构建保存 - 是完全不同的事情,彼此是不同的,因此,必须是以不同的方法执行,每种方法都有自己适当的错误处理代码。

像(伪代码):

...
entity = ...
// need to "build some relation" with entity
try {
call db_update_operation ((context) -> {
entities = fetch_from_context(context, ... fetch parameters ... )

connecting = entity.inContext(context)
for (relationed in entities)
relationed.entity = connecting
})
} catch () {
// dealing with errors, if any
// can get here within 3 situations:
// 1. there was error in fetch conditions
// 2. there was error in relations establishing
// 3. there was error in context saving
// each of that must be treated differently, like
// fetch/save errors should be passed to higher
// levels of abstraction, while relation-establishment
// errors can be processed here
}


func fetch_from_context( context, ... )

try {
fetched = context.fetch(..., &error)
} catch () {
// dealing with errors
// only fetch errors should be processed here
}

end

func db_update_operation( callback )

context = detauch_context (get_parent_context)

try {
callback(context)

try {
context.save(&error)
} catch () {
// dealing with save (and only save ) errors, if any
}

} finally {
// make sure, that we've relesed created context
// other errors is not our deal at this point
...
}
end

关于swift - 使用 Swift 2.0 处理 CoreData 中的顺序错误的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32515845/

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