Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can you find out if an NSObject has a certain property?

Let's say in Apple API version 1.0, there is a class NSFoo with a property 'color'. API 1.1 adds property 'size'.

I want to know whether I can use the getter: myFoo.size

[myFoo respondsToSelector:@selector(getSize)] doesn't work as expected.

What's the correct way to find out if an object has a property? Thanks!

like image 290
strawtarget Avatar asked Jun 17 '10 05:06

strawtarget


People also ask

How to check an object has a property?

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 do you check if an object has a property in TypeScript?

To check if a property exists in an object in TypeScript: Mark the specific property as optional in the object's type. Use a type guard to check if the property exists in the object. If accessing the property in the object does not return a value of undefined , it exists in the object.

Is property of object JavaScript?

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.

What is a NSObject?

The NSObject defines all things that are shared between all classes that extend from it: NSObject is the root class of most Objective-C class hierarchies. Through NSObject, objects inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.


1 Answers

You're close. Your selector should be exactly the message you want to send to the object:

if ( [myFoo respondsToSelector:@selector(size)] ) {
    int size = [myFoo size]; // or myFoo.size in dot-notation.
    // ...
}

should work.

like image 75
mbauman Avatar answered Oct 04 '22 21:10

mbauman