I am accessing a dispatched notification like so:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUnpresent:) name:UNPRESENT_VIEW object:nil];
...
-(void)handleUnpresent:(NSNotification *)note;
{
NSLog(@"%@", note.object.footer);
//property 'footer' not found on object of type 'id'
}
Some of the incoming note.object objects have a “footer” and some don’t. However, I don’t want to go through to trouble of making a class that only has a property called footer just to make this work. I even tried ((NSObject *)note.object).footer) which works in some languages, but apparently not obj-c. What can I do?
Checking the
isKindOfClassis certainly the more robust option. However, if you have multiple unrelated classes that return the property you need, there is another way:respondsToSelector. Just ask if the object has afootermethod, and you can safely call it.That
respondsToSelectormethod is powerful and handy in the right places, but don’t go wild with it. Also, it can’t tell you anything about the return type, so thefooteryou get may not be of the class you were expecting.The syntax for
noteObject.footerand[noteObject footer]are easy to treat as equivalent. However, when the class ofnoteObjectis unknown, the compiler will accept the latter but not the former. IfnoteObjecthas a defined class that doesn’t usually respond tofooter, it will give a warning, but still compile and run. In these cases, it is your responsibility to guarantee that the method will indeed exist when needed, and therefore that the method call won’t crash at run time.