Jan
Jan

Reputation: 2520

Objective c - Weird behavior with int

I have an object that stores a property as an int.

When in the console I type po menuItem.quantity I get a 1 which is what I'm expecting.

If I try to use that to populate a label with this line of code:

label_Quantity.text=[NSString stringWithFormat:@"%d", menuItem.quantity];

I instead get a 414280896

Also, please have a look at the following image:

enter image description here

For some reason it says _quantity = (int) 414280896but when I click on the i icon, I get a 1.

What is going on here?

EDIT 1:

Per a commenter's request, this is MenuItemDTO:

@interface MenuItemDTO : NSObject

@property (nonatomic) int menuItemID;
@property (nonatomic, strong) NSString* name;
@property (nonatomic, strong) NSString* description;
@property (nonatomic) int quantity;
@property (nonatomic, strong) NSString* imageURL;
@property (nonatomic) int categoryID;
@property (nonatomic) float price;
@property (nonatomic) BOOL isSponsoredItem;
@property (nonatomic, strong) NSDate* lastModifiedDate;

@end 

And it got created like this:

MenuItemDTO * menuItem = [MenuItemDTO new];
menuItem.quantity = [Converter fromDictionaryValueToInt:[json objectForKey:@"Quantity"]];

json is an NSDictionary with different values coming from a web service.

Converter fromDictionaryValueToInt looks like this:

+ (int)fromDictionaryValueToInt:(NSNumber *)value
{
    if ([value isKindOfClass:[NSNull class]])
        return 0;

    return [value intValue];
}

EDIT 2:

I found the problem, but don't understand why it didn't work. The problem didn't come when initializing. That was working just fine. It looks like later in the code, quantity was being assigned another value like this:

menuItem.quantity = (int)[dict objectForKey:@"Total"];

That was giving the problem with the weird number. Now I'm doing this:

menuItem.quantity = [Converter fromDictionaryValueToInt:[dict objectForKey:@"Total"]];

And it's working fine. If anyone can explain to me why the first method didn't work, I'll select that answer. Otherwise, I'll put this myself later and select mine.

Thanks to the commenters for helping me out.

Upvotes: 3

Views: 131

Answers (1)

gbitaudeau
gbitaudeau

Reputation: 2217

NSDictionnarycan only store NSObject, that means that when you call [dict objectForKey:@"Total"]it return a NSNumber * instead of an int and that's why your fromDictionaryValueToInt work.

If you write menuItem.quantity = (int)[dict objectForKey:@"Total"]; the (int) cast say to the compiler: I want to convert this NSNumber pointer address into an int so menuItem.quantity will receive the address and not the value.

Upvotes: 3

Related Questions