Sunday, October 14, 2012

Check for both null and nil to avoid crash - objective c

Sample code

line 1: NSString *someString;
line 2: someString = [self getStringValue];
line 3: NSLog(@"length of the string = %d",[someString length]);

In the above example sometimes the code can crash at line 3. Possible reason would be that the object "someString" is either null or nil. null vs nil has always been a debate with my friends, when to use and what to check and so on. If you don't have access to the contents of "getStringValue" method you'd probably have to check for both.

if (![someString isEqual:[NSNull null]] && (someString != nil)){
NSLog(@"length of the string = %d",[someString length]);
}

No comments: