我希望模拟与服务器的通信。由于远程服务器会有一些延迟,因此我想使用一个后台线程
[NSThread sleepForTimeInterval:timeoutTillAnswer];
使用NSThread子类创建线程并启动...但是我注意到sleepForTimeInterval会阻塞主线程...为什么???NSThread默认不是后台线程吗?
线程是这样创建的:
self.botThread = [[PSBotThread alloc] init];
[self.botThread start];
更多信息: 这是机器人线程子类。
- (void)main
{
@autoreleasepool {
self.gManager = [[PSGameManager alloc] init];
self.comManager = [[PSComManager alloc] init];
self.bot = [[PSBotPlayer alloc] initWithName:@"Botus" andXP:[NSNumber numberWithInteger:1500]];
self.gManager.localPlayer = self.bot;
self.gManager.comDelegate = self.comManager;
self.gManager.tillTheEndGame = NO;
self.gManager.localDelegate = self.bot;
self.comManager.gameManDelegate = self.gManager;
self.comManager.isBackgroundThread = YES;
self.comManager.logginEnabled = NO;
self.gManager.logginEnabled = NO;
self.bot.gameDelegate = self.gManager;
BOOL isAlive = YES;
// set up a run loop
NSRunLoop *runloop = [NSRunLoop currentRunLoop];
[runloop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
[self.gManager beginGameSP];
while (isAlive) { // 'isAlive' is a variable that is used to control the thread existence...
[runloop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}
}
- (void)messageForBot:(NSData *)msg
{
[self.comManager didReceiveMessage:msg];
}
我希望从主线程调用“messageForBot”... 同时后台线程应该调用主线程上的一个方法进行通信... 时间间隔的睡眠在gManager对象内部....
sleepForTimeInterval:
(它会在被调用时延迟当前线程)。 - WainsleepForTimeInterval
在哪里? - Wain