這是非常容易使用Objective-C相關聯的對象:
在您的標題:
@interface UIButton (MyCustomProperty)
@property (readwrite, retain, nonatomic) id myCustomProperty;
@end
在您的實現文件:
#include <objc/runtime.h>
/* Associated objects need a unique memory location to use as a key. */
static char MyCustomPropertyKey = 0;
@implementation UIButton (MyCustomProperty)
/* Use @dynamic to tell the compiler you're handling the accessors yourself. */
@dynamic myCustomProperty;
- (id)myCustomProperty {
return objc_getAssociatedObject(self, &MyCustomPropertyKey);
}
- (void)setMyCustomProperty: (id)anObject {
objc_setAssociatedObject(self, &MyCustomPropertyKey, anObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
這就是它!
請參見[子類UIButton添加屬性](http:// stackoverflow。com/questions/5500327/subclass-uibutton-to-add-a-property /) – Joe
出於興趣,你實際添加了什麼?這看起來像一個代碼味道給我。 –
我同意保羅的意見。這聽起來似乎沒有在這裏遵循MVC分離。按鈕不應該知道應用程序其餘部分發生了什麼。按鈕只是通知你的視圖控制器的狀態變化(按下,釋放等)。擁有該按鈕的視圖控制器應處理這些事件並自行檢索數據。 –