Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you tell if a key exists for an object using Key-Value Coding?

I'd like to test whether an object has a writeable @property in the iPhone SDK.

One possible way of doing this is to check the -valueForKey: method, but that seems rather inelegant!

Example:

  @try {     id *value = [instance valueForKey:@"myProperty"];   }   @catch (NSException * e) {     // Key did not exist   } 

Is there a better way of doing this?

like image 350
Ted Avatar asked Dec 08 '09 17:12

Ted


People also ask

How do you check if a key in an object exists?

There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.

How do you check whether a key exists in a JavaScript object or not?

Example 2: Check if Key Exists in Object Using hasOwnProperty() The key exists. In the above program, the hasOwnProperty() method is used to check if a key exists in an object. The hasOwnProperty() method returns true if the specified key is in the object, otherwise it returns false .

How do you check if a key is present in an array of objects JavaScript?

Using the indexOf() Method JavaScript's indexOf() method will return the index of the first instance of an element in the array. If the element does not exist then, -1 is returned.


1 Answers

If you are creating the object that is being checked, you could override valueForUndefinedKey: and setValue:forUndefinedKey to do something more useful than raising an exception.

If, on the other hand, you are trying to introspect objects you don't know about at runtime, you will have to use the runtime methods to do that. You can either use the objective-c runtime itself and call either class_copyPropertyList or protocol_copyPropertyList and deal with those, or use Foundation and call respondsToSelector on the object for the KVC getter/setters for a given property, e.g., for a property foo you would call something like [someObject respondsToSelector:NSSelectorFromString(@"foo")];.

like image 153
Jason Coco Avatar answered Sep 21 '22 20:09

Jason Coco