David David - 1 year ago 98
iOS Question

Sublassing NSMutableAttributedString returns SIGABRT on init

I created a subclass of NSMutableAttributedString in one of my projects to make a string that continually changes each character to one of the colors given in an array on init, but when I try to call the init method, I get a

on the


#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;



- (id)initStringWithColors:(NSArray *)colors withString:(NSString *)string
self = [super initWithString:string];
[self setColors:colors];
[self cycle];

return self;

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

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[RainbowString initWithString:]: unrecognized selector sent to instance 0x166778c0'


Okay, so just to test this, I created a test subclass of NSMutableAttributedString with absolutely no content. I just created the subclass and left it plain.


#import <Foundation/Foundation.h>

@interface Test : NSMutableAttributedString


I ran:

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

That ran and compiled fine. But then I ran:

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

Same error. Am I not allowed to subclass NSMutableAttributedString or something?

Answer Source

Your conclusion is correct. NS(Mutable)AttributedString is a class cluster, and subclassing those doesn't work. Pity the Apple documentation doesn't clearly identify it as one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download