views:

40

answers:

2

Is it possible to "link" UILabel text property with another NSString so that when this other NSString is changed also UILabel text property changes?

Example:

UILabel *label = [[UILabel alloc] init];  
NSString *str = @"labelText1";  
label.text = str;  
str = @"labelText2"; //after this assignment label.text is still "labelText1"
+2  A: 

In your question you haven't "changed" any objects - NSString instances are immutable, and you've just said that some variable points to one instance instead of another. Assuming that your string is really a property of some other model object, you could have your controller observe that property (with -observeValueForKeyPath:ofObject:change:context) and update the label every time it sees a change.

Graham Lee
Yes, you are right and i like the idea with observeValueForKeyPath!
troner
A: 

No, you can't. The property definition for 'text' is:-

@property(nonatomic, copy) NSString *text

which means the UILabel's setter method takes a copy of the string you assign. If it did not do this you would never be able to assign an autoreleased string to a UILabel, since the label's text would disappear or go crazy once the original string you assigned was deallocated, and you would end up being repsonsible for the memory management of UILabel's own text, which would not be a good situation.

The answer is to provide some mechanism to update the label's text whenever the string you're interested in changes. As @Graham Lee pointed out, this can never happen with an immutable string, but assuming your source text is changing mutably somewhere (a game score, say), then you should simply update the label whenever that happens. Again, as @Graham Lee pointed out, Cocoa provides observers, delegates and various other methods to make this relatively easy.

Echelon
1. The "text" property could be `retain` instead of `copy`. It isn't, specifically so you can't mutate ths tring under its feet. 2. The string does not need to be mutable, and it shouldn't be; you observe properties of objects, not objects themselves. I don't think NSString is KVC-compliant, and I'm not sure what key paths you'd observe.
tc.
Thanks for the downvote. We're both saying the same thing, except I'm emphasizing the fact that the property has a "copy" attribute, and you're emphasizing that fact that the data is immutable. They both add up to the same thing: the OP has source data (model, text, whatever you want to call it) that changes, and he needs to implement some kind of mechanism to update the UILabel.
Echelon