我要給UIButton自定義一個屬性,我這樣做的MyUIButton.h@interface MyUIButton : UIButton{ NSString *idx;
}@property (nonatomic,retain) NSString *idx;@endMyUIButton.m@implementation MyUIButton@synthesize idx;@end#import "MyUIButton.h"
MyUIButton *btn = ((MyUIButton *)[MyUIButton buttonWithType:UIButtonTypeRoundedRect]); btn.idx = @"abcd";然后報錯了:-[UIRoundedRectButton setIdx:]: unrecognized selector sent to instance 0x816b2a0
2 回答

慕標琳琳
TA貢獻1830條經驗 獲得超9個贊
你代碼中雖繼承了UIbutton重寫了init,但是未重寫buttonWithType:,所以在調用[MyUIButton buttonWithType:UIButtonTypeRoundedRect]
時實際上調用了父類的buttonWithType:
,父類的buttonWithType:
調用了某種UIButton
的init
。
為什么我說是某種UIButton
?因為UIButton
的buttonWithType:
可以生成不同類型的對象,這些對象都是UIButton的子類。(當然不可能生成MyUIButton
類型的對象,也就無法響應setIdx:
方法)
實際上,UIButton是一種聚類
,你不能直接繼承它。應當增加擴展,使用運行時增加關聯對象。注意.m中引入了#import <objc/runtime.h>
:
@interface UIButton (IdxProperty)@property (nonatomic,retain) NSString *idx;@end#import <objc/runtime.h>@implementation MyUIButton@dynamic idx;@end- (NSString *)idx { NSString *idx = objc_getAssociatedObject(self, @"kUIButtonIdxKey"); return idx; } - (void)setIdx:(NSString *)idx { objc_setAssociatedObject(self, @"kUIButtonIdxKey", idx, OBJC_ASSOCIATION_RETAIN); }
更干凈的寫法是給@"kUIButtonIdxKey"
加個宏。此處我寫的有點dirty
還是那句話,加強下面向對象的學習

梵蒂岡之花
TA貢獻1900條經驗 獲得超5個贊
-(id)buttonWithType:(UIButtonType)type{ [super buttonWithType:type]; self.idx = @"abcd"; }
- 2 回答
- 0 關注
- 193 瀏覽
添加回答
舉報
0/150
提交
取消