Sublassing NSMutableAttributedString returns SIGABRT in init

I created a subclass of NSMutableAttributedString in one of my projects to create a string that constantly changes each character to one of the colors specified in the array in init, but when I try to call the init method, I get sigabrt using the initWithString: .

RainbowString.h

 #import <Foundation/Foundation.h> @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; } 

Even if I just call [[RainbowString alloc] initWithString:@"Hello"]; I get the same error:

* Application termination due to an uncaught exception "NSInvalidArgumentException", reason: '- [RainbowString initWithString:]: unrecognized selector sent to instance 0x166778c0'

Update

Well, therefore, to test this, I created a test subclass of NSMutableAttributedString with absolutely no content. I just created a subclass and left it open.

test.h

 #import <Foundation/Foundation.h> @interface Test : NSMutableAttributedString @end 

I ran:

 [[NSMutableAttributedString alloc] initWithString:@"Hello"]; 

This is launched and compiled perfectly. But then I ran:

 [[Test alloc] initWithString:@"Hello"]; 

The same mistakes. Am I not allowed to subclass NSMutableAttributedString or something else?

+6
source share
2 answers

Your conclusion is correct. NS(Mutable)AttributedString is a cluster of classes, and subclassing these functions does not work. It is a pity that the Apple documentation does not explicitly identify it as one.

+6
source

For future search engines, this method may be convenient. This is a subclass of NSAttributedString that reimplementes the public interface of NSAttributedString by composition — calls to public methods are passed to the internal instance of NSAttributedString.

I would not use it for production code, but sometimes it is a useful starting point when you want to temporarily use aspects of NSAttributedString during development.

0
source

All Articles