2 回答

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
你代碼中雖繼承了UIbutton重寫了init,但是未重寫buttonWithType:,所以在調(diào)用[MyUIButton buttonWithType:UIButtonTypeRoundedRect]
時(shí)實(shí)際上調(diào)用了父類的buttonWithType:
,父類的buttonWithType:
調(diào)用了某種UIButton
的init
。
為什么我說是某種UIButton
?因?yàn)?code>UIButton的buttonWithType:
可以生成不同類型的對(duì)象,這些對(duì)象都是UIButton的子類。(當(dāng)然不可能生成MyUIButton
類型的對(duì)象,也就無法響應(yīng)setIdx:
方法)
實(shí)際上,UIButton是一種聚類
,你不能直接繼承它。應(yīng)當(dāng)增加擴(kuò)展,使用運(yùn)行時(shí)增加關(guān)聯(lián)對(duì)象。注意.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"
加個(gè)宏。此處我寫的有點(diǎn)dirty
還是那句話,加強(qiáng)下面向?qū)ο蟮膶W(xué)習(xí)

TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊
-(id)buttonWithType:(UIButtonType)type{ [super buttonWithType:type]; self.idx = @"abcd"; }
- 2 回答
- 0 關(guān)注
- 203 瀏覽
添加回答
舉報(bào)