Objective c 停止正在运行的方法
我想在短时间内停止当前正在运行的方法。。 我可以不使用任何线程执行此操作吗?使用NSTimer:Objective c 停止正在运行的方法,objective-c,Objective C,我想在短时间内停止当前正在运行的方法。。 我可以不使用任何线程执行此操作吗?使用NSTimer: - (void)doThing { [self doFirstPart]; [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(doSecondPart) userInfo:nil repeats:NO];
- (void)doThing
{
[self doFirstPart];
[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(doSecondPart)
userInfo:nil
repeats:NO];
}
- (void)doFirstPart { printf("Hello, "); }
- (void)doSecondPart { printf(" world!\n"); }
将方法拆分为
myMethodPartA
和myMethodPartB
。然后,在myMethodPartA
的末尾,使用以下行:
[self performSelector: @selector(myMethodPartB) withObject: yourArgument afterDelay: someNSTimeInterval]
如果需要将一组信息从
myMethodPartA
传递到myMethodPartB
,则可以将所有这些信息绑定到一个NSArray中,作为参数传递给myMethodPartB
,您可以始终使用sleep()
或usleep()
函数。NSThread
上可能也有一些方便的方法,具体取决于您使用的是什么(您通常只在一个线程上工作)。在主线程上这是个坏主意。如果你这样做,UI会在睡眠期间冻结。一般来说,我同意。但没有给出上下文。事实上,他特别要求“不使用任何线程”,因此所有performSelector:。。。从技术上讲,他们是直言不讳的。他想阻止其他方法无法完成的事情!