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

Viewed 18995

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?

4 Answers

The try/catch approach you propose in your question is the only reliable way of knowing whether valueForKey: will throw an exception.

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