Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Objective C, can you check if an object has a particular property or message?

Tags:

objective-c

I wat to do something like this:

if (viewController.mapView) [viewController.mapView someMethod]; 

However, if mapView is not a class variable, this crashes. How do I check if mapView exists?

like image 549
Andrew Johnson Avatar asked Oct 08 '09 01:10

Andrew Johnson


People also ask

How to check if object contains that property or not?

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.

How to check if property exists in object nodejs?

The first way is to invoke object. hasOwnProperty(propName) . The method returns true if the propName exists inside object , and false otherwise. hasOwnProperty() searches only within the own properties of the object.

What are Objective-C properties?

The Objective-C declared properties feature provides a simple way to declare and implement an object's accessor methods.

How do I find the class of an object in Objective-C?

[yourObject isKindOfClass:[a class]] // Returns a Boolean value that indicates whether the receiver is an instance of // given class or an instance of any class that inherits from that class.


2 Answers

For ordinary selectors, you can use respondsToSelector:. I'm not certain if this will work for new-style property access (as it appears you are using in this example). To test if a class responds to a given selector, use instancesRespondToSelector:.

like image 194
dcrosta Avatar answered Sep 23 '22 13:09

dcrosta


Also, As Jason poninted out here, you can also use NSSelectorFromString to dynamically check at runtime. E.g.

if ([self respondsToSelector:NSSelectorFromString(elementName)])  {     [self setValue:elementInnerText forKey:elementName]; } 
like image 28
Robert Avatar answered Sep 26 '22 13:09

Robert