wows
wows

Reputation: 11127

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 i.e NSLog(@"Does this work? %@", [response isSuccess]). So the code itself works - but THANK YOU to everyone for your suggestions for making this more efficient!

Upvotes: 3

Views: 1457

Answers (3)

Ash Furrow
Ash Furrow

Reputation: 12421

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.

Upvotes: 4

user1027503
user1027503

Reputation:

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.

Upvotes: 0

lnafziger
lnafziger

Reputation: 25740

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

Upvotes: 2

Related Questions