2

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?

Community
  • 1
  • 1
Avba
  • 14,822
  • 20
  • 92
  • 192
  • I think sub-classing is a no-no. Did you explore categories? Anyway I won't ask why you subclassed (not interested/you said not to), but I reckon you don't need to. – trojanfoe Dec 22 '15 at 11:12
  • the UILabel text property is an NSString and , I think, that's the reason why you're not getting 'MyString' object. Maybe you'll need to subclass UILabel as well and setting the text property as 'MyString'. https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/#//apple_ref/occ/instp/UILabel/text – enzo Dec 22 '15 at 11:16
  • subclassing `NSString` sounds like a bad idea. – luk2302 Dec 22 '15 at 11:20
  • 1
    @enzo That doesn't make sense. Even if the pointer to a class instance is to the base class, the sub-class still exists. It's the copying that is the issue, as stated by Wain. – trojanfoe Dec 22 '15 at 11:29
  • I agree that subclassing is bad - But swizzling is bad too. And when you swizzle UILabel:setText: sometimes you have no choice but to subclass NSString – Avba Dec 22 '15 at 11:37
  • @trojanfoe you're right – enzo Dec 22 '15 at 11:38

2 Answers2

6

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)

Wain
  • 118,658
  • 15
  • 128
  • 151
0

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.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • According to the documentation it is possible. At the end of the day I am using the underlying NSString foundation. And yes, I am brave :) – Avba Dec 22 '15 at 12:50
  • ```It is possible to subclass NSString (and NSMutableString), but doing so requires providing storage facilities for the string (which is not inherited by subclasses) and implementing two primitive methods.``` – Avba Dec 22 '15 at 12:50