问题描述
好,所以我有这个,但是它行不通:
Ok, so I have this, but it wont work:
@interface UILabel (touches)
@property (nonatomic) BOOL isMethodStep;
@end
@implementation UILabel (touches)
-(BOOL)isMethodStep {
return self.isMethodStep;
}
-(void)setIsMethodStep:(BOOL)boolean {
self.isMethodStep = boolean;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if(self.isMethodStep){
// set all labels to normal font:
UIFont *toSet = (self.font == [UIFont fontWithName:@"Helvetica" size:16]) ? [UIFont fontWithName:@"Helvetica-Bold" size:16] : [UIFont fontWithName:@"Helvetica" size:16];
id superView = self.superview;
for(id theView in [(UIView *)superView subviews])
if([theView isKindOfClass:[UILabel class]])
[(UILabel *)theView setFont:[UIFont fontWithName:@"Helvetica" size:16]];
self.font = toSet;
}
}
@end
如果我取出getter和setter方法,那么它不起作用,它告诉我我需要创建一些getter和setter方法(或使用@synthesize-但将@synthesize放在@implementation中也会引发错误).但是使用getter和setter方法,我得到一个EXC_BAD_ACCESS和一个崩溃.有任何想法吗?谢谢
If I take out the getter and setter methods then it doesn't work it tells me I need to create some getter and setter methods (or use @synthesize - but putting @synthesize in the @implementation throws an error too). But with the getter and setter methods I get an EXC_BAD_ACCESS and a crash. Any ideas? Thanks
汤姆
推荐答案
不可能通过类别(仅方法)将成员和属性添加到现有类中.
It is not possible to add members and properties to an existing class via a category — only methods.
一个可能的解决方法是编写"setter/getter-like"方法,该方法使用单例来保存变量,而该方法原来是成员.
One possible workaround is to write "setter/getter-like" methods, that uses a singleton to save the variables, that would had been the member.
-(void)setMember:(MyObject *)someObject
{
NSMutableDictionary *dict = [MySingleton sharedRegistry];
[dict setObject:someObject forKey:self];
}
-(MyObject *)member
{
NSMutableDictionary *dict = [MySingleton sharedRegistry];
return [dict objectforKey:self];
}
或-当然-写一个自定义类,该类继承自UILabel
or — of course — write a custom class, that inherits from UILabel
请注意,现在可以在运行时注入关联对象. Objective C编程语言:关联引用
Note that nowadays an associated object can be injected during runtime. The Objective C Programming Language: Associative References
这篇关于在类别界面/实现中设置新属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!