子类化NSMutableAttributedString在init上返回SIGABRT
我在我的一个项目中创建了一个NSMutableAttributedString的子类来创建一个字符串,该字符串不断地将每个字符更改为init中数组中给出的颜色之一,但是当我尝试调用init方法时,我在initWithString:
上获得了一个sigabrt
initWithString:
方法。
RainbowString.h
#import @interface RainbowString : NSMutableAttributedString @property (nonatomic) NSArray* colors; @property (nonatomic) NSTimeInterval duration; @property (nonatomic) NSTimer* timer; - (id)initStringWithColors:(NSArray*)colors withString:(NSString*)string; - (id)initStringWithColors:(NSArray*)colors withCycleDuration:(NSTimeInterval)duration withString:(NSString*)string; - (void)stop; - (void)start:(NSTimeInterval)duration; @end
initWithColors:
- (id)initStringWithColors:(NSArray *)colors withString:(NSString *)string { self = [super initWithString:string]; if(self) { [self setColors:colors]; [self cycle]; } return self; }
即使我只是调用[[RainbowString alloc] initWithString:@"Hello"];
, 我犯了同样的错误:
*由于未捕获的exception’NSInvalidArgumentException’而终止应用程序,原因:’ – [RainbowString initWithString:]:无法识别的选择器发送到实例0x166778c0′
更新
好的,为了测试这个,我创建了一个NSMutableAttributedString的测试子类,绝对没有内容。 我刚刚创建了子类并保持原样。
Test.h
#import @interface Test : NSMutableAttributedString @end
我跑了:
[[NSMutableAttributedString alloc] initWithString:@"Hello"];
那跑得很好。 但后来我跑了:
[[Test alloc] initWithString:@"Hello"];
同样的错误。 我不允许inheritanceNSMutableAttributedString或其他东西吗?
你的结论是正确的。 NS(Mutable)AttributedString
是一个类集群 ,并且对它们进行子类化不起作用。 遗憾的是Apple文档没有明确地将其标识为一个。
对于未来的搜索者来说, 这个要点可能很方便。 它是NSAttributedString的子类,它通过组合重新实现NSAttributedString的公共接口 – 对public方法的调用被传递给NSAttributedString的内部实例。
我不会将它用于生产代码,但有时当您想在开发期间临时检测NSAttributedString的各个方面时,它是一个有用的起点。