check if NSNumber is empty

后端 未结 5 1061
醉话见心
醉话见心 2021-02-07 05:28

How do I check if a NSNumber object is nil or empty?

OK nil is easy:

NSNumber *myNumber;
if (myNumber == nil)
    doSomething

But if th

5条回答
  •  执笔经年
    2021-02-07 05:59

    NSNumber is either nil, or it contains a number, nothing in between. “Emptiness” is a notion that depends on the semantics of the particular object and therefore it makes no sense to look for a general emptiness check.

    As for your examples, there are several things going on:

    NSMutableDictionary *hash = [NSMutableDictionary dictionary];
    [hash setObject:@"" forKey:@"key"];
    NSNumber *number = [hash objectForKey:@"key"];
    NSLog(@"%i", [number intValue]);
    

    The NSLog will print 0 here, but only because there’s an intValue method in NSString. If you change the message to something that only NSNumber can do, the code will fail:

    NSLog(@"%i", [number unsignedIntValue]);
    

    This will throw:

    -[NSCFString unsignedIntValue]: unrecognized selector sent to instance 0x303c
    

    Which means you are not getting some general “empty” value back from the hash, you just get the NSString you stored there.

    When you have an empty (== nil) NSNumber and send it a message, the result will be zero. That’s simply a language convention that simplifies code:

     (array != nil && [array count] == 0)
     (someNumber == nil ? 0 : [someNumber intValue])
    

    Will turn into this:

     ([array count] == 0)
     ([someNumber intValue])
    

    Hope this helps.

提交回复
热议问题