Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: How to use memory management properly for asynchronous methods

I need to call a method that starts some asynchronous code

MyClass* myClass = [[MyClass alloc] init];
[myClass startAsynchronousCode];

Now I can't simply release it as this would cause an error since the code is still running:

[myClass release];  // causes an error

What is the best way to deal with the memory?

like image 294
Robert Avatar asked Apr 23 '10 12:04

Robert


1 Answers

You could have -[MyClass startAsynchronousCode] invoke a callback:

typedef void(*DoneCallback)(void *);

-(void) startAsynchronousCode {
  // Lots of stuff
  if (finishedCallback) {
    finishedCallback(self);
  }
}

and then instantiate a MyClass like this:

MyClass *myClass = [[MyClass alloc] initWith: myCallback];

myCallback might look like this:

void myCallback(void *userInfo) {
  MyClass *thing = (MyClass *)userInfo;
  // Do stuff
  [thing release];
}
like image 132
Frank Shearar Avatar answered Oct 14 '22 18:10

Frank Shearar