objc_getAssociatedObject returns the wrong value

197 Views Asked by At

Below is the code to associate an extra value with a button

- (int)uniqueId
{
    return (int)objc_getAssociatedObject(self, uniqueIdStringKeyConstant);
}

- (void)setUniqueId:(int)uniqueId
{
    objc_setAssociatedObject(self, uniqueIdStringKeyConstant, [NSNumber numberWithInt:uniqueId], OBJC_ASSOCIATION_ASSIGN);
}

When I try to fetch the value of uniqueId it returns the wrong value.

[button1 setUniqueId:1];
NSLog(@"%d",[button1 uniqueId]); // in console it prints 18

Can any one please help me to find out what I am doing wrong?

2

There are 2 best solutions below

0
Ian MacDonald On BEST ANSWER

You are casting an NSNumber directly to an int, which will return you the value of the pointer address of the object.

What you wanted to do was:

return [(NSNumber *)objc_getAssociatedObject(self, uniqueIdStringKeyConstant) intValue];
0
Aaron Brager On

You're storing an NSNumber, and then casting it to int. You can't do that - casting doesn't change the data type.

Try this:

- (int)uniqueId
{
    NSNumber *number = objc_getAssociatedObject(self, uniqueIdStringKeyConstant);
    return number.intValue;
}