Search code examples
iosxcodelldbnsnull

ios: NSNull lldb error when using substringToIndex


I have the following code:

            NSString *subtitleFull = [dictionary valueForKey:@"distance"];                
            NSString *subtitle = [subtitleFull substringToIndex:2];

When I run the code I get the following error:

           -[NSNull substringToIndex:]: unrecognized selector sent to instance 0x3a61a080

I checked if the dictionary returns a NSString and it does with:

              id idont = [dictionary valueForKey:@"distance"];

              if ([idont isKindOfClass:[NSString class]]){
                  NSLog(@"*****************YEA THIS IS IT %@", idont);
              }

The string looks like this: "12.0093778471967" before it becomes type NSString. Maybe I need to use int value method?

Any reason why I get this error?


Solution

  • The error meesage is quite straightforward, subtitleFull is null. Since usually if a key doesn't exist the return should be nil. So in this case, I guess why a value in a dictionary is null is because the dictionary is from a JSON string or XML. Just check if the value is null before using it.