Just getting going with iPhone development and Objective-C
.
Yesterday I was trying to addObserver for a notification in a view of mine, and I kept getting this error:
unrecognized selector sent to instance
I tracked it down to the fact that I needed to include the trailing colon to my selector argument:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nameOfMySelector:) name:@"BBLocationServicesAreDisabled" object:nil];
Today, I thought I was clever because when setting up the action argument to a button, I remembered my mistake yesterday, and added the colon to the action argument. The action argument takes a @selector
, just like the selector argument while setting up an observer for an NSNotification
, so I figured I was doing the right thing.
However, with the following code:
[self.callToActionButton addTarget:self action:@selector(nameOfMySelector:) forControlEvents:UIControlEventTouchUpInside];
I get the exact same error:
unrecognized selector sent to instance
What gives? Why does one @selector
require a trailing colon, and the other doesn't? What are the rules I should follow for when it should be included and when it should be left off, and why I can't I always just do one or the other?
Thanks!
As mentioned by boltClock, the character you are referring to is actually a colon. The difference between @selector(method)
and @selector(method:)
is the method signature. The 2nd variant expects a parameter to be passed.
@selector(method)
would expect the method: -(void)method
@selector(method:)
would expect the method: -(void)method:(id)someParameter