tags:

views:

284

answers:

2

I see many Objective-C/Cocoa SDK apis where you can specify a target and an action that will get called back.

I want to do the same in two of my classes but when I store the passed in selector and later try to invoke it, I get the exception,

"unrecognized selector sent to instance"

I pass off to ClassB the target and action like this:

[myClassB doSomething:self action:@selector(anAction:)];

ClassB is declared and implemented as this:

@interface ClassB
{
   id  target;
   SEL targetAction;
}

@implementation ClassB 

-(void)theWork {
if ( [target respondsToSelector:targetAction] ) 
{
    [target targetAction];
}
}

During the build process, I also get the following warning:

no '-targetAction' method found

How can I invoke the target action that was supplied?

What I want to achieve is similar to this:

UIBarButtonItem *cancelButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
          target:self 
          action:@selector(cancelItem:)];
+2  A: 
[target targetAction];

means to run the method called targetAction.

you want

[target performSelector:targetAction];
David Maymudes
A: 

You need to store the selector name in your ivar:

ClassB *b = [[ClassB alloc] init];
SomeOtherClass *a = [[SomeOtherClass alloc] init];

// next two lines require properties to be declared
b.target = a;
b.targetAction = @selector(doTask:);

Now in ClassB you can invoke method on a with

[target performSelector:targetAction withObject:someObject];

That would invoke

- (void)doTask:(id)object

on class SomeOtherClass passing someObject to it.

Farcaller