lunes, 19 de diciembre de 2011

Execute methods asynchronously using NSOperation

Sometimes we want to run some methods in background, for example a service request.
Cocoa has a class ready for execute asynchronous methods, it's NSOperation. NSOperation is a key value coding and key value observing compilant, this means that you can observe some properties to perform different actions in your application, for example, if it finished executing (isExecuting).


  1. //We init a new queue
  2. //Create a new operation
  3. NSInvocationOperation *operation = [NSInvocationOperation alloc] initWithTarget:self selector:@selector(getAge:) object:@"Nicolas"];
  4. //Add operation to the queue
  5. [queue addOperation:operation];


Right here we are creating a new queue and adding an operation to it, this way the callback is in the queue and will be called asynchronously.
So we need to declare the callback


  1. -(void)getAge:(id)sender
  2. {
  3.    //Do magic
  4. }


In this case sender will be an (NSString *) object with value "Nicolas", but you can send whatever object you want as a parameter to the callback.

No hay comentarios:

Publicar un comentario