How to check for null value in NSNumber

后端 未结 3 652
孤街浪徒
孤街浪徒 2021-01-06 02:14

First off I confess my ignorance, I\'ve learned everything I know about Objective-C in the few months I\'ve been working on my project. I also find it utterly frustrating ho

相关标签:
3条回答
  • 2021-01-06 02:42

    In some cases, such as missing keys in NSUserDefaults, you get back the literal @"" as an empty string.

    Here's my safe check for an NSNumber.

    Note the check for it being an NSNumber occurs first because NSNumber doesn't understand isEqualToString

            id savedPin = [[NSUserDefaults standardUserDefaults] valueForKey:@"blah"];  // don't assume is created so don't type as NSNumber*
            if ( ![savedPin isKindOfClass:[NSNumber class]] && [savedPin isEqualToString:@""]) {  
    
    0 讨论(0)
  • 2021-01-06 02:51

    Use [shoObject class] to get the class of an object; so, to test shoObject's class, you would use

    [shoObject isKindOfClass:[NSString class]];
    

    Once you've sorted out what markers define an empty string or NSNumber, you can create a macro. I do with this by keeping an IsEmpty macro in a file called CommonMacros.h. Here's the code:

    //Thanks Wil
    //http://wilshipley.com/blog/2005/10/pimp-my-code-interlude-free-code.html
    
    static inline BOOL IsEmpty(id thing) {
        return thing == nil
        || ([thing isEqual:[NSNull null]]) //JS addition for coredata
        || ([thing respondsToSelector:@selector(length)]
            && [(NSData *)thing length] == 0)
        || ([thing respondsToSelector:@selector(count)]
            && [(NSArray *)thing count] == 0);
    }
    

    Then, after importing CommonMacros.h, you can call the function like this:

    if (IsEmpty(shotIndex)) {
        //do stuff
    }
    

    This should take care of this problem, and will also work on strings, arrays, etc, as you can see from the code. Thanks to Wil Shipley!

    0 讨论(0)
  • 2021-01-06 02:54

    In Objective-c, it's nil not null. So:

    if (shotIndex != nil) {
       // its not nil
    }
    
    0 讨论(0)
提交回复
热议问题