如何从另一个类访问ViewController中的IBOutlet



我有一个GCDAsyncUdpSocketDelegate类。现在我正在通过UDP(在后台线程中)获取一些数据,并且需要在ViewController中使用IBOutlet来显示这些数据。但ViewController只是一个类。它的对象实例定义在哪里?它叫什么名字?我该如何访问它,或者访问它的某个属性、方法?我见过这个UIApplication.sharedApplication().keyWindow?.rootViewController方法,但我想这并不能保证我想要访问的ViewController。

我不知道你的应用程序的确切结构,但你可以尝试这样的东西:

let rootViewController = UIApplication.sharedApplication().keyWindow?.rootViewController
if let customViewController = rootViewController as? CustomViewController {
    customViewController.label.text = theData
}
else{ 
    let customViewController = storyoboard!.instantiateViewControllerWithIdentifier("CustomViewControllerID")
    // (This assumes CustomViewController is defined in the same 
    // storyboard as the view controller running this code. Otherwise, 
    // you need to get a reference to the storyboard first).
    rootViewController.presentViewController(customViewController, animated:true)
    customViewController.label.text = theData
}

编辑:如果接收异步服务器数据的对象已从导航中删除(顺便说一句,调用不错),则可以使用它:

  1. 将数据存储在某个地方,即使所述对象已解除分配,数据也会持久存在(或者使所述对象成为单例(如果适用))。

  2. 一旦数据可用,就发布系统通知(使用NSNotificationCenter),并让主ViewController"监听"(-addObserver:selector:name:object)。当发布通知并调用通知处理程序时,视图控制器可以从其(持久)位置(文件,或上面提到的singleton的属性,如果您选择了该路由)检索数据。

  3. 最后,对于在实例化ViewController时数据已经可用的情况,请检查数据可用性并检索数据(如果存在于例如主视图控制器的viewDidLoad()中)。

有很多方法可以实现这一点,

1.使用协议或委托

您说"我有一个类是GCDAsyncUdpocketDelegate。"在该类中编写一个协议实现,并使视图控制器订阅该委托,当您获得GCDAsync乌普SocketDelegate的委托回调时,请进行必要的检查,并将自定义委托激发到视图控制器,将数据作为参数传递给委托方法。在视图中,控制器获取数据并更新IBOutlet。

2.使用NSNotificationCenter(肮脏的做事方式,但必须小心)

在你的视图控制器类中,为你要发布的通知添加一个观察者,比如

NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateUI:", name: "didRecieveDataFromUDP", object: nil)

在VC 中添加一个方法

 func updateUI(notifObject:NSNotification){
  let responseString = notifObject.object
  self.yourOutlet.string = responseString
}

并且当您完成VC时,还可以删除通知观察器。在GCDAsyncUdpSocketDelegate委托类中,当您获得带有结果的回调时,会触发此通知,

  NSNotificationCenter.defaultCenter().postNotificationName("didRecieveDataFromUDP"", object: theResposenObjectYouNeedToSend)

3.使用共享实例或错误使用AppDelegate(不推荐)

创建将贯穿应用程序生命周期的共享实例或单例类,并使用它们从任何类或任何线程存储/检索数据。

希望这有帮助,我希望你选择第一种或第二种方式。

最新更新