使用Swift 2.0处理CoreData中顺序错误的最佳实践
假设我做了这样的事情:使用Swift 2.0处理CoreData中顺序错误的最佳实践,swift,Swift,假设我做了这样的事情: do { try context.executeFetchRequest(..) // tweak the results // build a relation try context.save() } catch { ... } 对context.save的调用执行第二个do块更好,还是只按上面所示的顺序执行我的所有try调用更好 我的想法是,如果我想以不同的方式处理任何潜在的错误,最好将它们作为嵌套的do块来处理。类似地,如果您想处理相同的错误,则
do {
try context.executeFetchRequest(..)
// tweak the results
// build a relation
try context.save()
} catch { ... }
对context.save的调用执行第二个do块更好,还是只按上面所示的顺序执行我的所有try调用更好
我的想法是,如果我想以不同的方式处理任何潜在的错误,最好将它们作为嵌套的do块来处理。类似地,如果您想处理相同的错误,则应该连续执行这些操作。我的观点是,获取、建立关系和保存是完全不同的事情,它们彼此之间是完全不同的,因此,必须以不同的方法执行,每个方法都有自己适当的错误处理代码
与伪代码类似:
...
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