简体   繁体   中英

Comparing NSNumber value with defined int

I'm trying to store a constant int value to compare against in a particular scenario. My define looks like this:

#define kApiSuccessCode 0

And I have a method which compares a statuscode ( NSNumber ) with this to give a BOOL result:

- (BOOL)isSuccess {
    return [self.statusCode isEqualToNumber:[NSNumber numberWithInt:kApiSuccessCode]];
}

I have a synthesized NSNumber property like this:

@property (nonatomic, strong) NSNumber *statusCode;

The problem is I get a Execution was interrupted, reason: EXC_BAD_ACCESS error when running this code - I can't work out why? Is this a bad way to compare int values? Thanks

SOLVED:

Turns out I was making the basic mistake of trying to NSLog a BOOL value ie NSLog(@"Does this work? %@", [response isSuccess]) . So the code itself works - but THANK YOU to everyone for your suggestions for making this more efficient!

I don't know why the crash is occurring, but to answer your other question, yes, this is not a great way to compare int values.

There are valid reasons to store values in NSNumber instances, but in most cases it is overkill. If you do, in fact, have an NSNumber instance, just use intValue to get it's integer value and compare it to a primitive instead of creating a whole new instance.

If you look at Foundation classes, you'll see most of the time, they rely on NSInteger primitive types instead of NSNumber instances. For example, the NSURLResponse class uses an NSInteger to return the HTTP status code.

I would enable Zombies as instructed in this post .

It will then tell you if you are sending the message to a deallocated instance of the variable.

Once you figure this out, I would then suggest this instead:

- (BOOL)isSuccess {
    return [self.statusCode intValue] == kApiSuccessCode; 
}

Advantage and disadvantages of #define vs. constants?

As mentioned by others, #define doesn't have a type associated with it

=> kApiSuccessCode is not an integer, the pre-compiler just replace it with 0 before you program is compiled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM