David David - 1 month ago 14
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

sigabrt
on the
initWithString:
method.

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:


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


Update



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.

Test.h



#import <Foundation/Foundation.h>

@interface Test : NSMutableAttributedString

@end


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?

CRD CRD
Answer

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.

Comments