[英]Swift Completion Block
I want to achieve the following : 我要实现以下目标:
reloadDatabase()
is called within the completionBlock. reloadDatabase()
。 reloadDatabase()
will call getObjects()
in classA
to get the most updated list of database objects and pass to objectList
in classB reloadDatabase()
将在classA
调用getObjects()
以获取最新的数据库对象列表,并传递给objectList
中的objectList Question: How do i ensure that whenever i call getObjectList()
in classB, i will always get the most updated list? 问题:如何确保每当我在classB中调用
getObjectList()
时,我总是得到最新的列表? From my understanding, my objectList
might not be update in reloadDatabase() block
. 据我了解,我的
objectList
可能不会在reloadDatabase() block
更新。 I could be calling getObjectList()
when reloadDatabase()
haven't reach the completion block yet (objectList is still the old objectList). 当
reloadDatabase()
尚未到达完成块时,我可能正在调用getObjectList()
(objectList仍然是旧的objectList)。
I am pretty new to closures and blocks. 我对闭包和块很陌生。 Any guidance is greatly appreciated!
任何指导,不胜感激!
class classA: NSObject {
func addThisObject(object: RLMObject, completionBlock: () -> ())){
...
completionBlock()
}
func getObjects (completionBlock: ((list: [RLMObject]) -> ())){
var recordList = [RLMObject]()
...
completionBlock(list: recordList)
}
}
class classB: NSObject {
var objectList = [RLMObject]()
func addObject (object: RLMObject) {
classA().addThisObject(object, completionBlock: {() -> () in
self.reloadDatabase()
})
}
func reloadDatabase() {
classA().getObjects{(list) -> () in
self.objectList = list
}
}
func getObjectList() -> [RLMObject] {
return objectList
}
}
In your question, you don't say whether you'll be calling any of these functions from different threads. 在您的问题中,您没有说是否要从不同的线程调用这些函数中的任何一个。 So when you call addObject() in classB, execution wouldn't even continue until the database has been reloaded and objectList was updated.
因此,当您在classB中调用addObject()时,直到重新加载数据库并更新objectList为止,执行什至不会继续。
Using closures and blocks does not automatically imply that code will be executed on a different context. 使用闭包和块并不自动暗示代码将在不同的上下文中执行。
From your snippets it seems to me there is no asynchronous calls, so you won't be able to call getObjectList()
before reloadDatabase()
block. 从您的代码片段看来,我似乎没有异步调用,因此您将无法在
reloadDatabase()
块之前调用getObjectList()
。 Closures are not asynchronous if you don't use them with something that is (eg GCD). 如果您不将闭包与某些东西(例如GCD)一起使用,则它们不是异步的。
If you have asynchronous calls, but they are not in the snippets, then getObjectList()
can be called while reloadDatabase()
is being executed. 如果您有异步调用,但它们不在代码段中,则可以在执行
reloadDatabase()
调用getObjectList()
。 Then you have few options: 然后,您有几个选择:
updateInProgress
and check it in getObjectList()
- how to do it updateInProgress
并在getObjectList()
检查- 如何执行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.