我想子类UIButton添加一些我需要的属性(不是方法...只有属性).
这是我的子类的代码:
//.h-----------------------
@interface MyButton : UIButton{
MyPropertyType *property;
}
@property (nonatomic,retain) MyPropertyType *property;
@end
//.m--------------------------
@implementation MyButton
@synthesize property;
@end
Run Code Online (Sandbox Code Playgroud)
在这里我如何使用该类:
MyButton *btn = ((MytButton *)[MyButton buttonWithType:UIButtonTypeRoundedRect]);
btn.property = SomeDataForTheProperty;
Run Code Online (Sandbox Code Playgroud)
从哪里获得此错误:
-[UIRoundedRectButton setProperty:]: unrecognized selector sent to instance 0x593e920
Run Code Online (Sandbox Code Playgroud)
因此,从ButtonWithType我获得一个UIRoundedRectButton,(Mybutton *)不能施展它...我需要做什么来获得一个MyButton对象?是-init唯一的解决方案?
谢谢!
因为我们知道,我们可以添加使用类别和运行方法,如在Objective-C的变量
objc_setAssociatedObject和objc_getAssociatedObject.例如:
#import <objc/runtime.h>
@interface Person (EmailAddress)
@property (nonatomic, readwrite, copy) NSString *emailAddress;
@end
@implementation Person (EmailAddress)
static char emailAddressKey;
- (NSString *)emailAddress {
return objc_getAssociatedObject(self,
&emailAddressKey);
}
- (void)setEmailAddress:(NSString *)emailAddress {
objc_setAssociatedObject(self,
&emailAddressKey,
emailAddress,
OBJC_ASSOCIATION_COPY);
}
@end
Run Code Online (Sandbox Code Playgroud)
但有人知道做什么objc_getAssociatedObject或objc_setAssociatedObject做什么?我的意思是,我们添加到对象(这里self)的变量存储在哪里?和变量之间的关系self?