Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[NSNull isEqualToString:]

Im trying to set a string to "No Display name if [object objectForKey@"display_name"] is NULL". It crashing with this in the log

2011-06-16 10:58:36.251 BV API[15586:ef03] displayNameType is: NSNull
2011-06-16 10:58:36.251 BV API[15586:ef03] +[NSNull isEqualToString:]: unrecognized selector sent to class 0x1228c40
2011-06-16 10:58:36.253 BV API[15586:ef03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSNull isEqualToString:]: unrecognized selector sent to class 0x1228c40'
*** First throw call stack:
(0x1198f1c 0x132b52e 0x119bb2b 0x10f3076 0x10f2bb2 0x116d9 0x112ad 0x8b0e17 0x8b9783 0x8b43ae 0x8b9d20 0xb6312b 0x815c35 0xac2e1e 0x8b7583 0x8b771d 0x8b775d 0xc1b5 0x7ed84c 0x7ed7e2 0x89477a 0x894c4a 0x893ee4 0x813002 0x81320a 0x7f960c 0x7ecd52 0x211b8f6 0x116831a 0x10c3d07 0x10c1e93 0x10c1750 0x10c1671 0x211a0c3 0x211a188 0x7eac29 0x1b29 0x1aa5)
terminate called throwing an exceptionsharedlibrary apply-load-rules all
Current language:  auto; currently objective-c

NSString *displayNameType = (NSString *)[[object objectForKey:@"display_name"] class ];
NSLog(@"displayNameType is: %@", displayNameType);

NSString *displayNameString = [NSString stringWithFormat:@"%@", [object objectForKey:@"display_name"]];
displayNameString = [displayNameString uppercaseString];
if ([displayNameType isEqualToString:@"NSNull"]) {
    NSLog(@"dnt is null");
    NSString *displayNameString = @"No Display Name";
    displayNameString = [displayNameString uppercaseString];
}
like image 269
Sam Baumgarten Avatar asked Jun 16 '11 18:06

Sam Baumgarten


3 Answers

A cast will not change an object class (type).

You have to manage the case when your value is [NSNull null] with something like :

id displayNameTypeValue = [object objectForKey:@"display_name"];
NSString *displayNameType = @"";
if (displayNameTypeValue != [NSNull null])
   displayNameType = (NSString *)displayNameTypeValue;
like image 104
Vincent Guerci Avatar answered Sep 28 '22 11:09

Vincent Guerci


I created a category on NSNull, works well for me:

@interface NSNull (string)

-(BOOL) isEqualToString:(NSString *) compare;

@end

@implementation NSNull (string)

-(BOOL) isEqualToString:(NSString *) compare {    

    if ([compare isKindOfClass:[NSNull class]] || !compare) {
        NSLog(@"NSNull isKindOfClass called!");
        return YES;
    }

    return NO;  
}
@end
like image 21
Jerry Horton Avatar answered Sep 28 '22 09:09

Jerry Horton


You might want something like this:

NSString *displayNameType = NSStringFromClass([[object objectForKey:@"display_name"] class]);

And btw in your question, it shouldn't read "if it's NULL", but rather "if it's an NSNull instance".

like image 30
André Morujão Avatar answered Sep 28 '22 10:09

André Morujão