sFuller
sFuller

Reputation: 1385

Objective-C Property getter throwing exception 'Unrecognized selector sent to instance'

I'm new to Objective-C. I'm experiencing a problem trying to use a property getter. I have a property to access an instance of a very simple class. My interface looks like this:

@interface AppDelegate : UIResponder <UIApplicationDelegate>
//...
@property (strong, nonatomic, readonly) MyController* myController;
@end

And my implementation looks something like this:

@implementation AppDelegate
{
}

@synthesize myController = _myController;
....
//Getter
- (MyController*)myController
{
    return _myController;
}
@end

Elsewhere in my project I am trying to use the getter. It fails miserably.

AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication];
MyController* myController = appDelegate.myController; //unrecognized selector sent to instance

Being new to Objective-C, I'm sure I'm doing something horribly wrong. What's wrong here?

Upvotes: 0

Views: 766

Answers (1)

Carl Veazey
Carl Veazey

Reputation: 18363

Replace the call that instantiates appDelegate with the following:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

Right now you are sending a message to a UIApplication instance, rather than an instance of AppDelegate. Note that the return type of +[UIApplication sharedApplication] is UIApplication *, and the return type of -[UIApplication delegate] is id<UIApplicationDelegate> (at run time, assuming all is configured correctly, this delegate object will be an AppDelegate instance.

The error message would likely have given you a hint here - it would have probably been something like:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIApplication myController]: unrecognized selector sent to instance

The presence of UIApplication in the reason section tells you that the UIApplication class doesn't recognize this selector, while the - before the square brackets indicates that the message was sent to an instance of UIApplication. If you had sent an unrecognized selector to a class object, then the - would be replaced with a + (this is a common notation for communicating method signatures).

Upvotes: 4

Related Questions