[英]objc_getAssociatedObject returns the wrong value
以下是將額外值與按鈕關聯的代碼
- (int)uniqueId
{
return (int)objc_getAssociatedObject(self, uniqueIdStringKeyConstant);
}
- (void)setUniqueId:(int)uniqueId
{
objc_setAssociatedObject(self, uniqueIdStringKeyConstant, [NSNumber numberWithInt:uniqueId], OBJC_ASSOCIATION_ASSIGN);
}
當我嘗試獲取uniqueId
的值時,它將返回錯誤的值。
[button1 setUniqueId:1];
NSLog(@"%d",[button1 uniqueId]); // in console it prints 18
誰能幫助我找出我做錯了什么?
您要存儲一個NSNumber
,然后將其強制轉換為int
。 您無法做到這一點-強制轉換不會更改數據類型。
嘗試這個:
- (int)uniqueId
{
NSNumber *number = objc_getAssociatedObject(self, uniqueIdStringKeyConstant);
return number.intValue;
}
您正在將NSNumber
直接轉換為int
,這將為您返回對象的指針地址的值。
您想做的是:
return [(NSNumber *)objc_getAssociatedObject(self, uniqueIdStringKeyConstant) intValue];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.