在后台线程上调用函数

时间:2013-12-03 21:01:53

标签: ios multithreading sockets grand-central-dispatch outputstream

我是ios开发的新手,我正在使用tcp socket进行应用程序,并且遵循了几个教程,并且与连接相关的所有内容都很有效。但ui冻结,直到我的身份验证完成。对于此用途,“dispatch_queue”遵循

-(BOOL)Connect {

       queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
       dispatch_async(queue, ^ {
            CFReadStreamRef readStream;
            CFWriteStreamRef writeStream;
            CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)IP,PORT, &readStream, &writeStream);

            inputStream = (__bridge NSInputStream *)readStream;
            outputStream =(__bridge NSOutputStream *)writeStream;

           [inputStream setDelegate:self];
           [outputStream setDelegate:self];

           [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
           [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
           [inputStream open];
           [outputStream open];
           [[NSRunLoop currentRunLoop] run];

       });

    return true;

}

在这里,连接工作正常,不会锁定。现在我的问题是,当我在输出流上写东西时,不发送任何东西。 通过按下我需要向服务器发送内容的按钮来自另一个类,该函数被调用但不发送任何内容,因为它在我认为的另一个线程中。

-(void)Send:(NSMutableData *)_output{
   [outputStream write:[_output  bytes] maxLength:[_output length]];
 }

如果它在另一个线程中,我如何在outputstream中发送内容?

请原谅我的拼写,我说英语不多


阅读一些论坛,我发现NSThreads可以通过以下方式在它们之间传递数据:

performSelector:onThread:withObject:waitUntilDone:

但我不知道如何创建已经运行的线程实例。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

对于NS Thread,只需在函数中添加上述所有代码,然后调用它:

[self performSelectorOnMainThread:@selector(TcpSocketFunction) withObject:nil waitUntilDone:NO];

其中TcpSocketFunction是具有定义的函数名称。

- (void) TcpSocketFunction {
 CFReadStreamRef readStream;
            CFWriteStreamRef writeStream;
            CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)IP,PORT, &readStream, &writeStream);

            inputStream = (__bridge NSInputStream *)readStream;
            outputStream =(__bridge NSOutputStream *)writeStream;

           [inputStream setDelegate:self];
           [outputStream setDelegate:self];

           [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
           [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
           [inputStream open];
           [outputStream open];
           [[NSRunLoop currentRunLoop] run];
}