Scrungepipes
Scrungepipes

Reputation: 37581

Is it possible to cancel PerformSelector on multiple objects?

I have a few classes that can call performSelector:afterDelay.

In some circumstances I want to cancel any and all of them.

However all the cancelPerformSelector type methods take a target, thus it would seem there is no way to cancel everything in one go (as there are different targets)?

Unless specifying nil as the target will cancel everything?

Or could the target be specified as [NSRunLoop mainRunLoop] to cancel everything such as

[NSObject cancelPreviousPerformRequestsWithTarget:[NSRunLoop mainRunLoop]]

Upvotes: 3

Views: 1293

Answers (1)

Igor
Igor

Reputation: 4848

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.

Upvotes: 1

Related Questions