Search code examples
iosobjective-ciphoneassociated-object

objc_getAssociatedObject returns the wrong value


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?


Solution

  • 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];