Using a NSString subclass in UILabel et.al

74 Views Asked by At

I need to encode additional data to a NSString (Long story, please don't ask why...)

I've subclassed NSString using the method outlined here:

When I assign one of these subclasses as a UILabel's text I would expect to get it back when asking the labels text. But this isn't the case. (I get an NSString cluster instance instead)

MyString *string = [[MyString alloc] initWithString:@"Some string"];
UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
l.text = string;
NSString *t = l.text;  // not getting the "MyString" object

Is there a work around for this?

2

There are 2 best solutions below

0
On BEST ANSWER

The label copies the string:

@property (nonatomic, copy) NSString *text

so you at least need to implement copy to return your subclass type and copy your other data.

(not that subclassing is the best idea)

2
On

If you subclass NSString, you are braver than I would ever be, and you are totally on your own. NSString is a class cluster. You have basically not a chance in hell to subclass it and get it to work. It starts with the initialisation where [super init] which would be the NSString init method might return any kind of object.