gpt4 book ai didi

ios - ios 上的 SqlClient 在函数中的所有其他代码之后执行

转载 作者:行者123 更新时间:2023-11-28 15:44:20 25 4
gpt4 key购买 nike

我正在编写使用此项目的 IOS 应用程序:https://github.com/martinrybak/SQLClient .我在使用以下代码与 SQL 通信时遇到问题。它不会在第一次遇到 connect 函数时执行。它转到下一行,在 viewDidLoad 中完成所有代码后,它返回到我的连接方法,连接成功。如何让它先执行它的代码,然后再执行所有其他代码?这是我还不明白的 swift 和 ios 编程吗?

  override func viewDidLoad() {
super.viewDidLoad()

let client = SQLClient.sharedInstance()


client?.connect(Constants.serwerAdress, username: Constants.userName, password: Constants.password, database: Constants.databaseName) {
success in

if success {
client?.execute("select A FROM B") {
results in

for table in results as AnyObject! as! NSArray {
for row in table as AnyObject! as! NSArray {

for column in row as! NSDictionary {

print("\(column.key) = \(column.value)")
}
}
}
client?.disconnect()
}
}
}

DoSomethingElse()

}

最佳答案

移动你的 DoSomethingElse 以连接成功闭包。

override func viewDidLoad() {
super.viewDidLoad()

let client = SQLClient.sharedInstance()


client?.connect(Constants.serwerAdress, username: Constants.userName, password: Constants.password, database: Constants.databaseName) {
success in

if success {
client?.execute("select A FROM B") {
results in

for table in results as AnyObject! as! NSArray {
for row in table as AnyObject! as! NSArray {

for column in row as! NSDictionary {

print("\(column.key) = \(column.value)")
}
}
}
client?.disconnect()
DoSomethingElse()
}
}
}

}

代码中的方法,如 connect、execute 将闭包作为参数。这清楚地表明这些函数本质上是异步的,并且将异步执行 args。所以很明显你不能把它写成下一行来连接并在连接完成执行后执行。

编辑:

在连接/执行中调用 DoSomethingElse() 是处理这种情况的唯一方法吗?不。

我能想到的可能的解决方案:

  1. 您可以使用KVO。 :当连接/执行更新数据源时,将观察者设置为您的数据源,您可以调用您的 DoSomethingElse。如果你问我,我更喜欢更简洁的方法:)

  2. 使用 Semaphoresdispatch_semaphores(比信号量更好)来阻塞线程:完全不是建议的解决方案!!使用 semaphore/dispatch_semaphores 阻塞主线程可能会导致 iOS 因无响应而终止您的应用,并可能提供最差的用户体验。

  3. 使用Dispatch_Group : Dispatch_Group用于监控独立 block 的完成。这个可以考虑。但我更喜欢从闭包内部调用方法。保持代码更简洁:)

关于ios - ios 上的 SqlClient 在函数中的所有其他代码之后执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43345461/

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