Ios NSTimer不';你不能在NSThread中工作吗?

Ios NSTimer不';你不能在NSThread中工作吗?,ios,nstimer,nsthread,Ios,Nstimer,Nsthread,NSThread和NSTimer的一个非常简单的用法如下。当用户点击一个按钮时,我希望@“aaaaa”每秒打印一次,但@“aaaaa”只打印一次?看来NSTimer不起作用了…救命 //this method is connected to 'run' button in IB - (IBAction)begin1:(id)sender { [NSThread detachNewThreadSelector:@selector(thread1) toTarget:self withObj

NSThread和NSTimer的一个非常简单的用法如下。当用户点击一个按钮时,我希望@“aaaaa”每秒打印一次,但@“aaaaa”只打印一次?看来NSTimer不起作用了…救命

//this method is connected to 'run' button in IB
- (IBAction)begin1:(id)sender {
    [NSThread detachNewThreadSelector:@selector(thread1) toTarget:self withObject:nil];
}

-(void)thread1{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 
                                                      target:self
                                                    selector:@selector(aaa)
                                                    userInfo:nil
                                                     repeats:YES];
    [timer fire];
}

-(void)aaa{
    NSLog(@"aaaaa");
}

您没有保留计时器
+(NSTimer*)scheduledTimerWithTimeInterval:(NSTimeInterval)秒目标:(id)目标选择器:(SEL)选择器userInfo:(id)userInfo repeats:(BOOL)repeats
返回一个自动释放的NSTimer,因此如果您想确保它运行直到您告诉它停止为止,您应该将它保留在某个位置。

对于运行循环,计时器不是保持其运行的有效源。大概,您的运行循环看到它没有任何事情要做,然后退出,使其计时器无效——如果您的实际实现与编写的一样,情况就是这样。因此,您需要确保次线程的运行循环继续,以便计时器继续启动,因为该线程现在刚刚退出并使用计时器。

谢谢。似乎我也错过了创建NSTimer时的“NSRunLoop”。他为什么需要保留它?他没有在其他函数中使用它,它应该是可行的。或者你用弧?