1

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?

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
Tapas Pal
  • 7,073
  • 8
  • 39
  • 86

2 Answers2

2

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;
}
Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
2

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];
Ian MacDonald
  • 13,472
  • 2
  • 30
  • 51