简体   繁体   中英

Using a NSString subclass in UILabel et.al

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?

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM