Ios 如何从appdelegate共享NSOutputStream?

Ios 如何从appdelegate共享NSOutputStream?,ios,nsoutputstream,Ios,Nsoutputstream,我在appdelegate中设置了从应用程序启动到服务器的套接字连接。 在appdelegate.h中 @interface AppDelegate : NSObject <NSStreamDelegate,UIApplicationDelegate> { UIWindow *window; UITabBarController *tabBarController; NSInputStream *inputStream; NSOutputStream *ou

我在appdelegate中设置了从应用程序启动到服务器的套接字连接。 在appdelegate.h中

@interface AppDelegate : NSObject <NSStreamDelegate,UIApplicationDelegate> {
    UIWindow *window;
    UITabBarController *tabBarController;
    NSInputStream *inputStream;
 NSOutputStream *outputStream;
}
当应用程序启动时,它运行良好。沟通也很好

然后我有一个选项卡控制器。每个选项卡都需要通过该套接字向服务器交换数据。我不想为每个选项卡创建不同的套接字

如何使用相同的outputstream/inputstream

我在FirstViewControll.m中尝试此操作,但失败:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSData *data = [[NSData alloc] initWithData:[@"hello this is firstview" dataUsingEncoding:NSUTF8StringEncoding]];
 [outputStream write:[data bytes] maxLength:[data length]];
}

没有数据发送到服务器。我不想在每个viewcontroller到服务器上创建套接字。这浪费了太多的资源。我的问题是如何通过一个套接字连接发送/接收数据?

我将创建一个实用程序/管理器类来处理与服务器的通信。通过这种方式,您可以轻松地从代码的其他部分访问它。也很容易确保它是线程安全的。注意,您应该考虑不在主线程上执行这些操作。

但是,如果您确实希望访问AppDelegate中定义的变量,请参阅以下代码:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.outputStream <method>];
AppDelegate*AppDelegate=(AppDelegate*)[[UIApplication sharedApplication]委托];
[appDelegate.outputStream];

通过以下方式使用流:

AppDelegate *appDel = (AppDelegate *)[UIApplication sharedApplication].delegate;
[appDel.outputStream write:[data bytes] maxLength:[data length]];
[appDel.inputStream <CALL_YOUR_METHOD>];
AppDelegate*appDel=(AppDelegate*)[UIApplication sharedApplication]。委托;
[appDel.outputStream写入:[数据字节]最大长度:[数据长度]];
[appDel.inputStream];

如果我用服务器创建一个类来处理这个问题,我是否必须在每个选项卡上建立连接?如果没有,我还是会回到这个问题上来。我想它们应该是类似的东西。有多种方法可以共享对对象的访问。检查以下链接,了解如何使对象成为单例对象并从不同选项卡/类共享:是的,谢谢,outputstream正在工作。但我无法使inputstream工作。inputstream在appdelegate.m中工作正常,但firstviewcontroller.m中显示警告“NSInputstream可能不响应“方法”。appdelegate.m中已有一个方法响应inputstream。我想这两种方法是互相冲突的。是否有方法将变量从appdelegate.m传递到fristviewcontrol.m,然后激活另一个方法来执行其他操作?
AppDelegate *appDel = (AppDelegate *)[UIApplication sharedApplication].delegate;
[appDel.outputStream write:[data bytes] maxLength:[data length]];
[appDel.inputStream <CALL_YOUR_METHOD>];