且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查 NSNumber 中的空值

更新时间:2022-04-01 06:29:58

使用[shoObject class]获取对象的类;因此,要测试 shoObject 的类,您可以使用

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

[shoObject isKindOfClass:[NSString class]];

一旦您整理出定义空字符串或 NSNumber 的标记,您就可以创建一个宏.为此,我将 IsEmpty 宏保存在名为 CommonMacros.h 的文件中.代码如下:

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);
}

然后,导入CommonMacros.h后,可以这样调用函数:

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!