gpt4 book ai didi

ios - 新线程的问题

转载 作者:行者123 更新时间:2023-11-29 13:05:12 24 4
gpt4 key购买 nike

在尝试了很多方法在新线程中调用函数后,只有下面的代码对我有用

[NSThread detacNewThreadSelector:@selector(temp:) toTarget:self withObject:self];

以下无效:

NSThread *updateThread1 = [[NSThread alloc] initWithTarget:self selector:@selector(temp:) object:self];
NSThread *updateThread1 = [[NSThread alloc] init];
[self performSelector:@selector(temp:) onThread:updateThread1 withObject:self waitUntilDone:YES];

现在,当我尝试调用 NSTimer 或在 timer: 函数中执行选择器时,它不起作用在代码下方查找

int timeOutflag1 = 0;
-(void)connectCheckTimeOut
{
NSLog(@"timeout");
timeOutflag1 = 1;
}

-(void)temp:(id)selfptr
{
//[selfptr connectCheckTimeOut];
NSLog(@"temp");
//[NSTimer scheduledTimerWithTimeInterval:5 target:selfptr selector:@selector(connectCheckTimeOut) userInfo:nil repeats:NO];
[selfptr performSelector:@selector(connectCheckTimeOut) withObject:nil afterDelay:5];

}

- (IBAction)onUart:(id)sender {

protocolDemo1 *prtDemo = [[protocolDemo1 alloc] init];

//NSThread *updateThread1 = [[NSThread alloc] initWithTarget:self selector:@selector(temp:) object:self];
//[self performSelector:@selector(temp:) onThread:updateThread1 withObject:self waitUntilDone:YES];
// [updateThread1 start];
[self performSelector:@selector(temp:) withObject:self afterDelay:0];

while(1)
{
NSLog(@"Whieloop");
if(timeOutflag1)
{
timeOutflag1 = 0;
break;
}
if([prtDemo isConnected])
break;

}
}

如果我使用 [self performSelector:@selector(connectCheckTimeOut) withObject:nil afterDelay:5];onUart 函数中它可以正常工作,我可以看到 Timeout printf 但在 temp 中它不起作用。

最佳答案

NSTimer 是基于运行循环的,因此如果您想在自己生成和管理的后台线程上使用它,则需要在该线程上启动运行循环。阅读 NSRunLoop。简短版本可能类似于:

- (void)timedMethod
{
NSLog(@"Timer fired!");
}

- (void)threadMain
{
NSRunLoop* rl = [NSRunLoop currentRunLoop];
NSTimer* t = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: @selector(timedMethod) userInfo:nil repeats:YES];
[rl run];
}

- (void)spawnThread
{
[NSThread detachNewThreadSelector: @selector(threadMain) toTarget:self withObject:nil];
}

关于ios - 新线程的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18826929/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com