为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

iOS
慕容708150 2023-04-15 22:18:03
我要给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:调用了某种UIButtoninit

为什么我说是某种UIButton?因为UIButtonbuttonWithType:可以生成不同类型的对象,这些对象都是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

还是那句话,加强下面向对象的学习


查看完整回答
反对 回复 2023-04-18
?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

-(id)buttonWithType:(UIButtonType)type{
  [super buttonWithType:type]; 
   self.idx = @"abcd";
}


查看完整回答
反对 回复 2023-04-18
  • 2 回答
  • 0 关注
  • 95 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信