gpt4 book ai didi

ios - 回调中的 Swift UI 更新有时不执行

转载 作者:可可西里 更新时间:2023-11-01 01:06:10 26 4
gpt4 key购买 nike

当执行下面的代码时,我看到回调执行(通过“成功!”验证),但 UI activityIndi​​cator 上的 activityIndi​​cator 不会停止旋转。

有时它会在 10-20 秒后停止,有时它会一直运行。回调应该在主线程上运行,所以我不确定是什么导致它延迟/失败。

activityIndicator.startAnimating()
loadData("data") {(success: Bool) in
if success {
// I see this being printed
println("success!")
}

// This isn't updating on the UI! The wheel keeps spinning
self.activityIndicator.stopAnimating()
}

loadData 函数正在使用 Core Data 执行 block 保存:

public func loadData(completionHandler: (success: Bool) -> Void) {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let appContext = appDelegate.managedObjectContext!
let managedContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
managedContext.persistentStoreCoordinator = appContext.persistentStoreCoordinator

managedContext.performBlock({

//NSManagedObject inserts - working...

if !managedContext.save(&error) {
completionHandler(success: false)
}
completionHandler(success: true)
})
}

非常感谢这里的任何帮助!

最佳答案

    activityIndicator.startAnimating()
loadData("data") {(success: Bool) in
if success {
// I see this being printed
println("success!")
}

dispatch_async(dispatch_get_main_queue()) {
// This isn't updating on the UI! The wheel keeps spinning
self.activityIndicator.stopAnimating()
}
}

我还注意到,如果出现错误,您将调用完成 block 两次。因此,在第一个完成 block 之后添加一个返回。像这样:

public func loadData(completionHandler: (success: Bool) -> Void) {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let appContext = appDelegate.managedObjectContext!
let managedContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
managedContext.persistentStoreCoordinator = appContext.persistentStoreCoordinator

managedContext.performBlock({

//NSManagedObject inserts - working...

if !managedContext.save(&error) {
completionHandler(success: false)
return
}
completionHandler(success: true)
})

关于ios - 回调中的 Swift UI 更新有时不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29400361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com