我对如何运行以下代码感到有些失落。我的意图是只有在尝试成功时才执行onCompletion。那么延迟关闭应该在试验内还是之后呢? - 或者我完全走错了路。
此...
func addUserActivity(aUserActivity:UserActivity, onError:OnError, onCompletion: (Void) -> (Void)) {
if let database = database {
do {
try database.write({
database.add(aUserActivity)
defer {
onCompletion()
}
})
} catch {
onError(message: "Realm error",informativeText: "Realm database failed to write object")
}
}
}
或者这......
func addUserActivity(aUserActivity:UserActivity, onError:OnError, onCompletion: (Void) -> (Void)) {
if let database = database {
do {
try database.write({
database.add(aUserActivity)
})
defer {
onCompletion()
}
} catch {
onError(message: "Realm error",informativeText: "Realm database failed to write object")
}
}
}
还是完全不同的东西?
答案 0 :(得分:1)
在任何一种情况下,都不需要defer
。您只需撰写onCompletion()
。
如果你在onCompletion()
区块内拨打write
,总是会被执行,但如果你在try database.write{...}
之后写,那么onCompletion将是如果write
引发错误,则会跳过,这听起来像是您想要的行为。
(由OP编辑以包括最终解决方案)
<强>解强>
func addUserActivity(aUserActivity:UserActivity, onError:OnError, onCompletion: (Void) -> (Void)) {
if let database = database {
do {
try database.write({
database.add(aUserActivity)
})
onCompletion()
} catch {
onError(message: "Realm error",informativeText: "Realm database failed to write object")
}
}
}