3

我有几个类可以调用 performSelector:afterDelay。

在某些情况下,我想取消所有这些。

但是,所有 cancelPerformSelector 类型的方法都采用一个目标,因此似乎没有办法一次性取消所有内容(因为有不同的目标)?

除非指定 nil 作为目标会取消一切吗?

或者可以将目标指定为 [NSRunLoop mainRunLoop] 以取消所有内容,例如

[NSObject cancelPreviousPerformRequestsWithTarget:[NSRunLoop mainRunLoop]]
4

1 回答 1

1

Assuming you have a view controller declared similar to the following:

@interface CarViewController : UIViewController

@property (strong) id myObject;

@end

Also assuming you've registered the request for perform selector with the myObject instance somewhere in your implementation like the code below:

[self.myObject performSelector:@selector(someSelector) withObject:nil afterDelay:0.0];

For sake of argument, you want your view controller to cancel all the previous perform requests before it is unloaded from memory, your -viewWillUnload message would look like:

- (void)viewWillUnload {
    [NSObject cancelPreviousPerformRequestsWithTarget:self.myObject]
}

This would cancel all the perform requests registered for that particular instance. As Joe pointed out, if you are not keeping a strong reference to your objects by yourself and you're storing those objects in a NSArray, you need to iterate that array and call +cancelPreviousPerformRequestsWithTarget: for each element of the array, or even NSArray's -enumerateObjectsUsingBlock::

- (void)viewWillUnload {
    [myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [NSObject cancelPreviousPerformRequestsWithTarget:obj];
    }];
}

Hope this helps.

于 2012-06-06T10:29:47.180 回答