Run code only after asynchronous function finishes executing(仅在异步函数执行完毕后运行代码)
问题描述
总体而言,我对 Swift 和 Xcode 还比较陌生,并且在试图弄清楚这一点时发现了很多困难.
I am relatively new to Swift and Xcode in general and am finding a lot of difficulty trying to figure this out.
我正在开发一个利用 Parse.com
后端服务器的应用程序.为了不阻塞主线程,每当应用程序从服务器下载任何内容时,它都会在不同的线程上异步完成.然而,其余代码继续在主线程上执行,当它应该从服务器获得的数据尚未下载时,它会崩溃.我想知道如何在异步函数完成后调用函数来运行,这必须为单独文件中的函数完成.
I am developing an app that utilizes the Parse.com
backend server. In order not to block the main thread, whenever the app downloads anything from the server, it is done on a different thread, asynchronously. However the rest of the code continues to execute on the main thread, and it crashes when the data it is supposed to have from the server has not downloaded yet. I would like to know how to call functions to run after the asynchronous function finishes, and this has to be done for functions in separate files.
我读到闭包可能对此有所帮助,但我发现语法非常困难,非常感谢您的解释.但是任何方式都会很有帮助.
I read that closures might help with this, but I found there syntax very difficult and an explanation would be greatly appreciated. But any way would be very helpful.
谢谢
推荐答案
好吧,你只需在异步回调的末尾调用函数.那是异步回调结束的时候 - 这是异步回调中的其他所有内容都完成的时候!所以,例如:
Well, you simply call the function at the end of the asynchronous callback. That is when the asynchronous callback has ended - it is when everything else in the asynchronous callback has finished! So, for example:
func myMethod() {
// ... code ...
somebody.doSomethingWith(someObject, asynchronousCallback: {
(thing, otherThing) in
// ... do whatever
// --> CALL THE FUNCTION!
})
// ... code ...
}
如果问题是你不知道调用什么函数,你可以配置你周围的函数/对象,以便有人可以递给你一个函数,然后你在上面我说调用函数"的地方叫什么.
If the problem is that you do not know what function to call, you can configure your surrounding function / object so that someone can hand you a function which is then what you call in the spot where I said "call the function" in the above.
例如:
func myMethod(f:() -> ()) { // we receive the function as parameter
// ... code ...
somebody.doSomethingWith(someObject, asynchronousCallback: {
(thing, otherThing) in
// ... do whatever
// --> CALL THE FUNCTION, by saying:
f()
})
// ... code ...
}
这篇关于仅在异步函数执行完毕后运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:仅在异步函数执行完毕后运行代码


基础教程推荐
- NSString intValue 不能用于检索电话号码 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- iOS4 创建后台定时器 2022-01-01