![](/img/trans.png)
[英]Can invoking iOS main thread operation from background queue interrupt a method call?
[英]Can I call static method from background queue in swift?
我在ServerCommunication
类中有一个静态的getData()
方法,可以从后台队列中调用此方法。
//ServerCommunication.swift
import UIKit
import Foundation
class ServerCommunication
{
class func getData(url: String, sessionId: String) -> ServerResponse {
//server communication code goes here
}
}
func populateData() {
DispatchQueue.global(qos: .background).async {
let response = ServerCommunication.getData(url: URL, sessionId: "")
}
}
谁能解释会对线程执行产生什么影响?或者我是否需要将ServerCommunication
类定义为Singleton?
从后台队列调用时,多次执行getData()静态类
#Edit1更多说明
当我尝试在发出Push通知时尝试打开特定的viewController
时发生此问题。 我正在使用一个名为FAPanelController的第三方库,该库分别接受一个中心,左和右viewController。
代码示例:
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//Now I want to open a viewController
if let panel = self.window?.rootViewController as? FAPanelController
{
let centerNavVC = storyboard.instantiateViewController(withIdentifier: "HomeViewController") as! UINavigationController
let vc = centerNavVC.topViewController as! HomeViewController
panel.center(centerNavVC, afterThat: {
//HomeViewController has a method populateData() in viewWillAppear()
})
}
}
您可以为此使用Closures
class ServerCommunication
{
class func getData(url: String, sessionId: String, success: @escaping ((_ responseObject: ServerResponse?) -> Void)) {
//server communication code goes here
success(serverData) // serverData is a server response
}
}
func populateData() {
ServerCommunication.getData(url: "", sessionId: "", success: { (response) in
// You can handle response here
print(response)
})
}
我能想到的任何影响都有几个原因:
1.在某些时候,您的getData
会修改UI,我相信这里不是这样。
2. getData
修改外面的任何变量。 因此,您需要将这些修改包装在同步队列中。
3. getData
调用其他变异方法。 解决方案与2
相同。
否则,从任何地方调用您的静态方法都是安全的。 除非您需要为呼叫进行其他设置,否则不需要Singleton方法。
是的,您可以在后台线程中调用静态方法。
ClassName.performSelector(inBackground: #selector(self.ClassMethod), with: nil)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.