Cocoa touch 如何选择NSThread而不是NSTimer?
换句话说,如果我有一个连续运行的进程,但用户可以更改GUI上影响进程操作特征的参数,那么将进程放在Cocoa touch 如何选择NSThread而不是NSTimer?,cocoa-touch,nstimer,nsthread,Cocoa Touch,Nstimer,Nsthread,换句话说,如果我有一个连续运行的进程,但用户可以更改GUI上影响进程操作特征的参数,那么将进程放在NSThread或NSTimer?NSThread和NSTimer不是互斥的,也不是相互替代的。NSThread允许您控制执行线程,而NSTimer只是一个计时器 我想你是说在后台线程而不是主线程上运行NSTimer?这通常是一个好主意,这样计时器就不会因为主线程上发生的事情(例如用户与应用程序的交互)而延迟 您应该阅读。虽然和是两种不同需要的东西,但让我们比较两种功能: 使用NSThread: -
NSThread
或NSTimer
?NSThread和NSTimer不是互斥的,也不是相互替代的。NSThread允许您控制执行线程,而NSTimer只是一个计时器
我想你是说在后台线程而不是主线程上运行NSTimer?这通常是一个好主意,这样计时器就不会因为主线程上发生的事情(例如用户与应用程序的交互)而延迟
您应该阅读。虽然和是两种不同需要的东西,但让我们比较两种功能:
使用NSThread
:
-(void) doSomethingEverySecond {
__block int cumValue = 0; // cumulative value
__block void(^execBlock)() = ^{
while (1)
{
@try
{
// some code here that might either A: call continue to continue the loop,
// or B: throw an exception.
cumValue++;
NSLog(@"Cumulative Value is: %i", cumValue);
if (cumValue == 5)
return;
}
@finally
{
[NSThread sleepForTimeInterval:1];
}
}
};
[NSThread detachNewThreadSelector:@selector(invoke) toTarget:[execBlock copy] withObject:nil];
}
使用NSTimer
:
-(void) doSomethingEverySecond {
__block NSTimer *timer = nil;
__block int cumValue = 0;
__block void (^execBlock)() = ^{
cumValue++;
NSLog(@"Cumulative Value is: %i", cumValue);
if (cumValue == 5)
[timer invalidate];
};
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:[execBlock copy] selector:@selector(invoke) userInfo:nil repeats:YES];
}
现在,如果我们只想做一次某件事,NSThread
是一种方法,如下所示:
-(void) doSomethingOnce {
__block void (^execBlock)() = ^{
NSLog(@"Doing something that could take a LONG time!");
};
[NSThread detachNewThreadSelector:@selector(invoke) toTarget:[execBlock copy] withObject:nil];
}
现在,对于NSTimer
变体:
-(void) doSomethingOnce {
__block void (^execBlock)() = ^{
NSLog(@"Doing something that could take a LONG time!");
};
[NSTimer scheduledTimerWithTimeInterval:0 target:[execBlock copy] selector:@selector(invoke) userInfo:nil repeats:NO];
}
原因是,我们在使用NSThread
时可以完全控制线程,但如果使用NSTimer
,则在nsrunlop
中执行,如果在内部执行任何重载操作,则可能会冻结UI。这就是NSThread
优于NSTimer
的优点
您还可以保证,已分离的NSThread
会立即执行,而基于nsrunlop的NSTimer
不会立即执行,因为它可能会或可能无法立即执行
还有第三种选择(从技术上讲也是第四种,
pthread
s,但我现在将忽略它),GCD
,但我建议您在这方面进行RTFM,因为这篇文章的主题太宽泛了。它们是针对两个不同事物的两个独立结构,不可比较。