Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

For future searchers, this gist may be handy. It's a sub-class of NSAttributedString that re-implements the public interface of NSAttributedString via composition - calls to the public methods are passed through to an internal instance of NSAttributedString.

I wouldn't use it for production code, but sometimes it's a useful starting point when you want to temporarily instrument aspects of NSAttributedString during development.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top