Saturday, May 11, 2013

NSInvocationOperation initWithTarget selector object example ios


initWithTarget: selector: object:

Returns an NSInvocationOperation object initialized with the specified target and selector.
- (id)initWithTarget:(id)target selector:(SEL)sel object:(id)arg
Parameters
target
The object defining the specified selector.
sel
The selector to invoke when running the operation. The selector may take 0 or 1 parameters; if it accepts a parameter, the type of that parameter must be id. The return type of the method may be void, a scalar value, or an object that can be returned as an id type.
arg
The parameter object to pass to the selector. If the selector does not take an argument, specify nil.
Return Value( NSInvocationOperation initWithTarget selector object example )
An initialized NSInvocationOperation object or nil if the target object does not implement the specified selector.
Discussion( NSInvocationOperation initWithTarget selector object example )
If you specify a selector with a non-void return type, you can get the return value by calling the resultmethod after the operation finishes executing. The receiver tells the invocation object to retain its arguments.
( NSInvocationOperation initWithTarget selector object example )
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
               selector:@selector(loadImagesWithOperation:)
                 object:params];

( NSInvocationOperation initWithTarget selector object example )
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
NSDictionary *argumentDictionary = [NSDictionary dictionaryWithObjectsAndKeys:object1, @"Object1Key", object2, @"Object2Key", nil];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(methodCall:) object:argumentDictionary];
[queue addOperation:operation];
[operation release];

( NSInvocationOperation initWithTarget selector object example )
- (void)myMethod:(NSDictionary*)parameters 
{
    int a = [[parameters objectForKey:@"A"] intValue];
    int b = [[parameters objectForKey:@"B"] intValue];

    // do something with a and b
}


[[NSInvocationOperation alloc] 
    initWithTarget:self
          selector:@selector(myMethod:)
            object:[NSDictionary dictionaryWithObjectsAndKeys:
                     [NSNumber numberWithInt:123], @"A",
                     [NSNumber numberWithInt:456], @"B",
                     nil]];