1

I would like to subclass UILabel in such a way that the user of the class cannot set the text directly through label.text = @"foo". Instead I'd like to set the text from inside the subclass depending on some values.

What I tried:

BalanceLabel.h:

@interface BalanceLabel : UILabel
@property(nonatomic,copy, readonly)   NSString *text;
@end

However, I get a warning telling me I'm restricting text access (like I wanted to) but I don't get any compile time errors if I try to set the text directly using an object of my subclass.

jscs
  • 63,694
  • 13
  • 151
  • 195
Marcel Batista
  • 722
  • 6
  • 16

2 Answers2

3

You can't do this. As a trivial example as to why not, just think of how the following code should behave:

UILabel *label = [[BalanceLabel alloc] init];
label.text = @"string";

That code creates a BalanceLabel, but stores it in a variable of type UILabel, which means that the subsequent setting of the .text property can't know that you tried to make the property readonly in BalanceLabel.

Unfortunately there's not much you can do about this. You could override the setter to throw an exception, which will let users know what they did wrong, but of course will also crash the app.

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
1

You should be putting the logic into controller that managed the view instead of view directly.

  • I assume you have some view that gets updated with new values and you want to update the BalanceLabel based on these new values.
  • Your controller is a delegate for your view so it receives new values, from either user or other modules of your app that populated new values (like loaded from file, downloaded from network and so on).
  • Your controller then figures out which bits of view needs update and sets new values - in your case calculate balance, I assume
stefanB
  • 77,323
  • 27
  • 116
  • 141
  • Actually I just want to make some kind of labels like a date label, a balance label and stuff like that so I don't have to put everywhere in my code the formatting for such labels. For instance, a DateLabel would have a setDate:(NSDate*) date method that would format the date and set the string correctly after parsing and whatnot. I just want to avoid having to use a NSDateFormatter or something like that anytime I need to do this in my many screens. Thank you for your thoughts though! =) – Marcel Batista Nov 05 '13 at 19:30