Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Swift 2.0处理CoreData中顺序错误的最佳实践_Swift - Fatal编程技术网

使用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