我唯一的理论是,这是因为我没有在要停止的实际方法中调用 return 而是在不同的方法中调用
你的理论是正确的。return
结束它所在的函数或方法,仅此而已。它将当前函数的上下文从堆栈中弹出并将执行返回给调用函数。
我不太确定如何解决这个问题,因为据我所知,计时器只能指向其他方法,我不能只告诉它我想要它在我想要停止的方法中做什么
我们可以使用对象来存储状态并使用该状态来控制程序的流程。该状态可以不断更新和检查。对于需要取消以响应状态变化的长时间运行的任务,状态必须与任务并行更新。既然您说计时器用于停止音频,但所做的工作method
却没有,我假设method
它已经异步执行其长时间运行的任务。
这需要在后台执行一个异步长时间运行的任务(或一系列任务),并有可能取消,与NSOperation
andNSOperationQueue
类很好地匹配。
您可以NSOperation
通过实现方法或块在对象内部执行您的工作。实施您的代码以检查操作是否已在所有适当的时间被取消,并在发生这种情况时立即退出。
下面是一个希望与您的用例匹配的示例。它是在 iOS 应用程序“空应用程序”模板中创建的,所有内容都在应用程序委托中。我们的应用程序委托跟踪做出是否取消决定所需的状态,并安排一个计时器来轮询该状态的更改。如果它确实确定应该取消,它将实际取消工作委托给操作队列及其操作。
#import "AppDelegate.h"
@interface AppDelegate ()
@property (nonatomic) BOOL shouldStop; // Analogous to your isRecording variable
@property (nonatomic, strong) NSOperationQueue *operationQueue; // This manages execution of the work we encapsulate into NSOperation objects
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Typical app delegate stuff
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
// Start our long running method - analogous to method in your example
[self method];
return YES;
}
- (void)method
{
// allocate operation queue and set its concurrent operation count to 1. this gives us basic ordering of
// NSOperations. More complex ordering can be done by specifying dependencies on operations.
self.operationQueue = [[NSOperationQueue alloc] init];
self.operationQueue.maxConcurrentOperationCount = 1;
// We create three NSBlockOperations. They only sleep the thread a little while,
// check if they've been cancelled and should stop, and keep doing that for a few seconds.
// When they are completed (either through finishing normally or through being cancelled, they
// log a message
NSMutableArray *operations = [NSMutableArray array];
for (int i = 0; i < 3; i++) {
// Block operations allow you to specify their work by providing a block.
// You can override NSOperation to provide your own custom implementation
// of main, or start, depending. Read the documentation for more details.
// The principle will be the same - check whether one should cancel at each
// appropriate moment and bail out if so
NSBlockOperation *operation = [[NSBlockOperation alloc] init];
// For the "weak/strong dance" to avoid retain cycles
__weak NSBlockOperation *weakOperation = operation;
[operation addExecutionBlock:^{
// Weak/strong dance
NSBlockOperation *strongOperation = weakOperation;
// Here is where you'd be doing actual work
// Either in a block or in the main / start
// method of your own NSOperation subclass.
// Instead we sleep for some time, check if
// cancelled, bail out if so, and then sleep some more.
for (int i = 0; i < 300; i++) {
if ([strongOperation isCancelled]) {
return;
}
usleep(10000);
}
}];
// The completion block is called whether the operation is cancelled or not.
operation.completionBlock = ^{
// weak/strong dance again
NSBlockOperation *strongOperation = weakOperation;
NSLog(@"Operation completed, %@ cancelled.", [strongOperation isCancelled] ? @"WAS" : @"WAS NOT");
};
[operations addObject:operation];
}
// Set up a timer that checks the status of whether we should stop.
// This timer will cancel the operations if it determines it should.
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(checkShouldKeepGoing:) userInfo:nil repeats:YES];
// Use GCD to simulate a stopped recording to observe how the operations react to that.
// Comment out to see the usual case.
double delayInSeconds = 5;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
self.shouldStop = YES;
});
// Add the operations to the operation queue, exeuction will start asynchronously from here.
[self.operationQueue addOperations:operations waitUntilFinished:NO];
}
// If we should stop, cancel the operations in the queue.
- (void)checkShouldKeepGoing:(NSTimer *)timer
{
if (self.shouldStop) {
NSLog(@"SHOULD STOP");
[timer invalidate];
[self.operationQueue cancelAllOperations];
}
}
@end