首先UIButton是个类簇,用buttonWithType:方法返回的就不一定是哪个类的对象,可能是UIButton,可能是UIRoundedRectButton,也可能是你自己定义的子类(Custom时)。
同样的还有NSValue等类都是类簇结构。
所以,[myCard
buttonWithType:UIButtonRoundedRect];返回的是一个UIRoundedRectButton对象,而你继承的是UIButton,和UIRoundedRectButton是并行关系,所以,set自定义属性的时候自然出错。这是类簇中类方法面临的问题,他return的是具体类的实例。
我提供点解决方案:
1.看你的类名是Card,估计用Custom的几率比较大,所以如果是Custom的话,因为是个空的button什么都不需要draw,所以会返回你自定义类的对象。
myCard*
nButton=[myCard
buttonWithType:UIButtonTypeCustom];没问题,可以正常使用。
2.如果你非要添加属性,并且非要用所有type的话,那么就只能利用UIButton的类别,为所有button类型添加动态属性。我实例一下:
复制代码
@interface UIButton(Pr)
@property (nonatomic, retain) NSNumber
*cardId;
//- (void)setCardId:(int)aCardId;
//-
(int)cardId;
@end
@implementation UIButton(Pr)
@dynamic
cardId;
- (id)cardId {
return objc_getAssociatedObject(self,
@"KCardId");
}
- (void)setCardId:(NSNumber *)newCardId
{
objc_setAssociatedObject(self, @"KCardId", newCardId,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
注意,类别声明要在使用之前,这个大家应该都明白,我就不啰嗦了。还要记得
#import
如果大家有更好的方式,可以提出,一起讨论啊。