我想暂停线程操作的用户的行动,这是在后台运行。我使用NSTimer
来暂停线程,但是当我按暂停按钮时,我的所有程序(屏幕)冻结,我无法按任何按钮。
NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(calculationOfPIValue)
userInfo:nil
repeats:YES];
我不确定我是否正确理解了你想做什么。
你有一个后台线程(运行它通过NSThread
?NSOperation
吗?GCD
?) .
因此,要在后台运行PI计算并启用取消它,您可以使用NSOperation
。
创建一个名为MyPiCalculationOperation
的新类,并键入:
#import <Foundation/Foundation.h>
@interface MyPiCalculationOperation: NSOperation
@end
@implementation MyPiCalculationOperation
- (void)main {
@autoreleasepool {
// paste your calculate PI algorithm, I put here any loop as an example
for (int i = 0; i < 100; i++) {
// in your loop check isCancelled flag
if (self.isCancelled) {
break;
}
}
}
}
@end
请参阅http://nshipster.com/nsoperation/。
在您的控制器中,您应该在某处开始操作。下面只是一个例子,因为我不知道你想什么时候开始:
@property (nonatomic, readonly) NSOperationQueue *queue;
- (void)viewDidLoad {
[super viewDidLoad];
self.queue = [[NSOperationQueue alloc] init];
MyPiCalculationOperation *operation = [[MyPiCalculationOperation alloc] init];
[self.queue addOperation:operation]; // this will auto-start when you add operation to the queue
}
- (IBAction)buttonPressedDown:(id)sender { // your button press handler
[self.queue cancelAllOperations]; // to cancel
// or use setSuspended to "pause" the operations
}