难道我这样扩展属性不对么?

我要给UIButton自定义一个属性,我这样做的

MyUIButton.h

@interface MyUIButton : UIButton{    NSString *idx;
}@property (nonatomic,retain) NSString *idx;@end

MyUIButton.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
慕容708150
浏览 140回答 2
2回答

慕标琳琳

你代码中虽继承了UIbutton重写了init,但是未重写buttonWithType:,所以在调用[MyUIButton buttonWithType:UIButtonTypeRoundedRect]时实际上调用了父类的buttonWithType:,父类的buttonWithType:调用了某种UIButton的init。为什么我说是某种UIButton?因为UIButton的buttonWithType:可以生成不同类型的对象,这些对象都是UIButton的子类。(当然不可能生成MyUIButton类型的对象,也就无法响应setIdx:方法)实际上,UIButton是一种聚类,你不能直接继承它。应当增加扩展,使用运行时增加关联对象。注意.m中引入了#import <objc/runtime.h>:@interface&nbsp;UIButton&nbsp;(IdxProperty)@property&nbsp;(nonatomic,retain)&nbsp;NSString&nbsp;*idx;@end#import&nbsp;<objc/runtime.h>@implementation&nbsp;MyUIButton@dynamic&nbsp;idx;@end-&nbsp;(NSString&nbsp;*)idx {&nbsp;&nbsp;&nbsp;&nbsp;NSString&nbsp;*idx&nbsp;=&nbsp;objc_getAssociatedObject(self,&nbsp;@"kUIButtonIdxKey");&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;idx; } -&nbsp;(void)setIdx:(NSString&nbsp;*)idx { &nbsp;&nbsp;&nbsp;&nbsp;objc_setAssociatedObject(self,&nbsp;@"kUIButtonIdxKey",&nbsp;idx,&nbsp;OBJC_ASSOCIATION_RETAIN); }更干净的写法是给@"kUIButtonIdxKey"加个宏。此处我写的有点dirty还是那句话,加强下面向对象的学习

梵蒂冈之花

-(id)buttonWithType:(UIButtonType)type{ &nbsp;&nbsp;[super&nbsp;buttonWithType:type];&nbsp; &nbsp;&nbsp;&nbsp;self.idx&nbsp;=&nbsp;@"abcd"; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

iOS