Search code examples
objective-ciosxcodeperformancerespondstoselector

Performance penalty using respondsToSelector


I will be refactoring a lot of old code to make the client more robust to bad server responses and log exceptions whenever the JSON response has invalid values, and I am thinking of checking the validity (data type) for each node being parsed using respondsToSelector.

I am checking for a data type (int, bool etc) in the response

[[json objectForKey: @"feature_enabled"] boolValue], 

which crashes the app if the @"feature_enabled" node has anything other than 0 or 1

to get around this issue, here's how I'd do it

if ([[json objectForKey: @"feature_enabled"] respondsToSelector: @selector(boolValue)]){
          BOOL featureEnabled = [[json objectForKey: @"feature_enabled"] boolValue];
}else{
          Log Exception
}

I haven't done any kind of performance analysis on this code, but I'd like to know if anyone can suggest what kind if performance penalty I should expect if I am going to check responds to selector for every JSON response I intend to parse.

Any pointers to the sources of info appreciated!


Solution

  • You may want to consider using isKindOfClass which I believe is the best performance:

    if([[yourDictionary objectForKey:@"yourKey"] isKindOfClass:[NSArray class]]) { //assume its an array and handle it }