Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-[NSNull objectForKeyedSubscript:]: unrecognized selector sent to instance

Tags:

objective-c

I got an exception that says:

-[NSNull objectForKeyedSubscript:]: unrecognized selector sent to instance

Is it saying I am trying to access an NSNull object with a key? Any idea what causes this and how to fix it or debug further?

like image 279
Boon Avatar asked Mar 06 '13 01:03

Boon


3 Answers

The way to fix it is to not attempt objectForKeyedSubscript on an NSNull object. (I'm betting you're handling some JSON data and aren't prepared for a NULL value.)

(And apparently objectForKeyedSubscript is what the new array[x] notation translates into.)

(Note that you can test for NSNull by simply comparing with == to [NSNull null], since there's one and only one NSNull object in the app.)

like image 144
Hot Licks Avatar answered Oct 17 '22 10:10

Hot Licks


What ever value you are storing, despite what the editor tells you, at run time you are storing an NSNull, and later on trying to call objectForKeyedSubscript. I am guessing this happening on what is expected to be an NSDictionary. Some thing like:

NSString *str = dict[@"SomeKey"]

Either a piece of code beforehand is not doing its job and investigate there, or perform some validation:

NSDictionary *dict = ...;

if ( [dict isKindOfClass:[NSDictionary class]] ) {
    // handle the dictionary
}
else {
   // some kind of error, handle appropriately
}

I often have this kind of scenario when dealing with error messages from networking operations.

like image 37
Mike D Avatar answered Oct 17 '22 12:10

Mike D


I suggest adding a category to NSNull to handle this in the same way you would expect a subscript call to be handled if it it were sent to nil.

@implementation NSNull (Additions)

- (NSObject*)objectForKeyedSubscript:(id<NSCopying>)key {
    return nil;
}

- (NSObject*)objectAtIndexedSubscript:(NSUInteger)idx {
    return nil;
}

@end

A simple way to test is like this:

id n = [NSNull null];
n[@""];
n[0];

With this category, this test should be handled successfully/softly.

like image 1
Spencer Hall Avatar answered Oct 17 '22 11:10

Spencer Hall