在swift中的视图之间传递NSInpuStream和outputStream

时间:2014-08-07 09:27:39

标签: ios swift

我有2个视图都需要一个NSInputStream和一个NSOutputStream变量,我的问题是如何从第二个中的第一个获取输入流/ outpustream。

第一个ViewController

class ViewController: UIViewController,NSStreamDelegate{
 var inputStream : NSInputStream!
 var outputStrean : NSOutputStream!
 override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    self.initNetworkCommunication()

 } 

 func initNetworkCommunication() {
 //here i init the both of them
 }

}

现在第二个应该使用相同的东西,不必再次在服务器中重新连接[执行相同的initNetworkCommunication]。

class ViewController2: UIViewController,NSStreamDelegate {
 var inputStream : NSInputStream!
 var outputStrean : NSOutputStream!

 override func viewDidLoad() {
    super.viewDidLoad()
    inputStream = ???
    outputStrean =???
 }
}

我尝试过使用getter但是在某些情况下,我在函数调用

中获得了一个额外的参数

更新: 仔细看后我仍然面临这个问题。因为我使用了一个读取和写入流,我用

启动
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,"localhost",8023,&readStream,&writeStream)
   inputStream = self.readStream!.takeUnretainedValue()
    outputStrean = self.writeStream!.takeUnretainedValue()

在遵循建议并从第一个viewController中的一个启动读取流后,我得到一个错误,它们是null。问题是我想避免从单个用户到服务器的多个连接,此时此是唯一可行的方式

1 个答案:

答案 0 :(得分:1)

试试这个。

您可以通过编写协议或以其他方式将数据传递给ViewController类对象来获取它。

让我们看看如何将数据传递给对象。

class ViewController1: UIViewController {

 override func viewDidLoad() {
    super.viewDidLoad()

 }

  func getViewController(storyBoard: NSString) -> UIViewController
    {
        var mystoryBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        var ViewControllerID : UIViewController = mystoryBoard.instantiateViewControllerWithIdentifier(storyBoard) as UIViewController
        return ViewControllerID
    }

func buttonClickedFunction()
{
 var viewController2Object : ViewController2 = getViewController("ViewController2StoryBoardName") as ViewController2
viewController2Object.inputStream = "" // give the value which you want to pass to the ViewController2
viewController2Object.outputStream = ""//  give the value which you want to pass to the ViewController2
  self.presentViewController(viewController2Object, animated: true, completion: nil)
}
}




class ViewController2: UIViewController {

 var inputStream : NSInputStream!
 var outputStrean : NSOutputStream!

 override func viewDidLoad() {
    super.viewDidLoad()
     inputStream // use this values in code
    outputStream // use this values in code
 }
}