Jon
Jon

Reputation: 4732

Why is my NSNumber always nil?

So for some reason, in a certain method, my NSNumber is always nil and its driving me nuts.

If the user selects a row in my picker, this gets called and it works fine:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    self.query.activityLevel = [NSNumber numberWithInt:[[[self.activityArray objectAtIndex:row]objectForKey:@"key"]intValue]];
}

However, when the user doesn't pick a row, and just continues to the next VC, I have a check to see if activityLevel is nil and to set it to 1 if so.

- (void)donePressed {
    if (!self.query.activityLevel) {
        self.query.activityLevel = [NSNumber numberWithInt:2];
    }
    NSNumber *calories = [Calculations numberOfCaloriesNeededForQuery:self.query];
    [self dismissModalViewControllerAnimated:YES];
}

The problem is, whenever the user doesn't pick a row and it hits self.query.activityLevel = [NSNumber numberWithInt:2];, if I print the object, it is still nil. I have no idea why. I set a breakpoint and it is hitting that line...

Upvotes: 3

Views: 256

Answers (1)

aleroot
aleroot

Reputation: 72646

Maybe you get nil because the value of self.query is also nil, so you are setting a value on nil object and you get nil ...

It is a little bit confusing but while in another language you usually get a NullPointer exception in these kind of situations, in objective C it is legal to send a message to nil so keep attention at these situations ...

Upvotes: 4

Related Questions