【发布时间】:2011-06-11 03:15:22
【问题描述】:
我在 iPhone 上使用 AsyncSocket 与服务器通信。 AsyncSocket 基于运行循环,但我的应用程序基于线程。这意味着,我启动一个新线程来写入数据并等到在同一个线程上收到响应。但是我不能直接从另一个线程调用 AsyncSocket 的方法,我必须使用:
[self performSelectorOnMainThread:@selector(writeSomeData:) withObject:dataToWrite waitUntilDone:YES];
它确实有效,但我无法从以这种方式调用的方法“writeSomeData:”获得响应,因为 performSelectorOnMainThread 什么也不返回。
方法 writeSomeData: 做了这样的事情:
-(NSData *)writeData:(NSData *)dataToWrite {
dataReceived = nil; // AsyncSocket writes data to this variable
[asyncSocket writeData:dataToWrite withTimeout:-1 tag:0];
[asyncSocket readDataToData:[@"<EOF" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
int counter = 0;
while (dataReceived == nil && counter < 5) {
// runLoop is [NSRunLoop currentRunloop]
[runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.3]];
++counter;
}
return [dataReceived copy];
}
我可以通过访问类变量“dataReceived”来获得响应,但此时它的内容发生了变化。
谁能告诉我如何在单独的线程上使用 AsyncSocket(或者一般来说,如何处理基于运行循环的类),这样如果我调用该类的方法,它会阻塞,直到该方法被执行并收到响应?
谢谢。
【问题讨论】:
-
你为什么首先想要那个场景?如果(看似)您要做的第一件事就是阻止它直到某个或多或少任意的未来日期,为什么要创建一个线程?为什么不从带有 runloop 的线程开始整个事情并分派 result-data 以在
NSOperationQueue或全局并发dispatch_queues 之一上进行处理?
标签: iphone cocoa-touch nsthread asyncsocket nsrunloop