在开发过程中经常使用到多线程。对ios的多线程有很多不解的地方,这里暂且记录下来。具体原因有待以后慢慢研究。
1、看了一些文章介绍,说苹果建议将涉及界面更新的代码放在主线程里面处理。这个还好理解一点。但在实际使用中,发现即使是一些数据逻辑处理的代码,在线程中处理也是有问题。
例如:在线程中创建AsyncUdpSocket对象,代码如下:
-(void)scanLoop
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//...省略部分代码
{
static NSInteger localHostBase = LOCAL_BIND_PORT;
AsyncUdpSocket *_udpSocket = [[[AsyncUdpSocket alloc] initWithDelegate:self] autoRelease];
BOOL bind = [_udpSocket bindToPort:localHostBase++ error:nil];
NSAssert(bind, @"bing port %d failed!", localHostBase - 1);
[self performSelectorOnMainThread:@selector(processIpScanWithSocket:) withObject:_udpSocket waitUntilDone:NO];
[NSThread sleepForTimeInterval:0.01]; //10ms
}
}
[pool release];
}
以AsyncUdpSocket对象为参数的处理函数,如下所示:
-(void)processIpScanWithSocket:(AsyncUdpSocket*)_udpSocket
{
char *bytes = UDPSCANDATA_SENDTO_SRV;
NSData *dataToSend = [[NSData alloc] initWithBytes:bytes length:strlen(bytes)];
BOOL send = [_udpSocket sendData:dataToSend toHost:aServerIp port:UDPSCAN_PORT withTimeout:-1 tag:0];
NSAssert(send, @"send data failed!");
[_udpSocket receiveWithTimeout:-1 tag:0];
[dataToSend release];
self.udpSocket = _udpSocket;
[_udpSocket release];
}
无论是在线程中直接调用[self processIpScanWithSocket:_udpSocket]还是调用
[self performSelectorOnMainThread:@selector(processIpScanWithSocket:) withObject:_udpSocket waitUntilDone:NO];
都得不到服务器返回的响应消息。经过调试,服务器是收到消息的,并且成功发送返回包。在程序中得不到响应,猜想因为是AsyncUdpSocket对象的delegate无效。如果将创建AsyncUdpSocket对象的代码放在主线程处理,一切就正常了。可以得到从服务器返回的数据。
将以上代码改为下面的代码,一切都正常。代码如下:
-(void)processIpScanWithSocket
{
static NSInteger localHostBase = LOCAL_BIND_PORT;
AsyncUdpSocket *_udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
BOOL bind = [_udpSocket bindToPort:localHostBase++ error:nil];
NSAssert(bind, @"bing port %d failed!", localHostBase - 1);
char *bytes = UDPSCANDATA_SENDTO_SRV;
NSData *dataToSend = [[NSData alloc] initWithBytes:bytes length:strlen(bytes)];
BOOL send = [_udpSocket sendData:dataToSend toHost:aServerIp port:UDPSCAN_PORT withTimeout:-1 tag:0];
NSAssert(send, @"send data failed!");
[_udpSocket receiveWithTimeout:-1 tag:0];
[dataToSend release];
self.udpSocket = _udpSocket;
[_udpSocket release];
}
//线程处理函数
-(void)scanLoop
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//...省略部分代码
{
[self performSelectorOnMainThread:@selector(processIpScanWithSocket) withObject:nil waitUntilDone:NO];
[NSThread sleepForTimeInterval:0.01]; //10ms
}
}
[pool release];
}
不知是自己用法问题还是实际存在这种情况。主程序的对象不能在线程中处理,不然会出现一些问题,例如delegate无效。没有搞明白其中的原因,暂且记录,以后有时间再仔细研究一下。