16

I ran in to a EXC_BAD_ACCESS when deallocating an object that has few performSelector:withObject:afterDelay where the selector methods is calling another object and I am releasing the object.

Somewhere in my class I am calling:

[self performSelector:@selector(callObject1Function) withObject:nil afterDelay:2.0];

and in my class I have:

- (void)callObject1Function{
    [object1 function1]  // Here I am getting "EXC_BAD_ACCESS"
}

- (void)dealloc {
    [object1 release];
    [super dealloc];
}

I just don't understand I thought when you dealloc it the object, everything associated with the object should be removed or canceled, even the performSelector with delay!

Cœur
  • 37,241
  • 25
  • 195
  • 267
Unis
  • 365
  • 1
  • 4
  • 13

2 Answers2

28

Use NSObject's:

-cancelPreviousPerformRequestsWithTarget:selector:object: 

to cancel any pending perform selectors.

KlimczakM
  • 12,576
  • 11
  • 64
  • 83
Ben Gottlieb
  • 85,404
  • 22
  • 176
  • 172
  • 18
    Also just NSObject's +cancelPreviousPerformRequestsWithTarget: if you want to eliminate all selector and object perform requests to that target without specifying selectors and objects – Bogatyr Aug 25 '10 at 09:48
  • You should cancelPreviousPerformRequestsWithTarget with the same target, the same selector and the *same* object. If the object is different, you didn't cancel anything. Important. – Leonardo May 20 '23 at 13:55
24

I have used following code in my all apps and it's working.

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(MethodName) object:nil];

Thanks, Hemang.

Hemang
  • 1,224
  • 9
  • 15