How to check for null value in NSNumber

后端 未结 3 679
孤街浪徒
孤街浪徒 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: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!

提交回复
热议问题