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!
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With