Reputation: 239
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"
Upvotes: 2
Views: 1312
Reputation: 7922
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.
Upvotes: 0
Reputation:
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.
Upvotes: 5