Reputation: 144
aClass.aString = @"A";
self.aLabel.text = aClass.aString;
If I change aClass.aString to "B", also want self.aLabel.text change to "B" automatically.
How it works?
Is there a strong link exist that I can built between aClass.aString and self.aLabel.text? I knew that there some way to do this in objective-c, delegate and KVO, but it get a lot stuff to do, it's there some easy way?
Upvotes: 1
Views: 1252
Reputation: 13222
One more way other than overriding the setter method,
- (void)setAString:(NSString *)aString
is using KVO to observe change in the string value.
[self addObserver: self
forKeyPath: @"aString"
options: NSKeyValueObservingOptionNew
context: NULL];
Implement this method. It will get called whenever the string value changes.
-(void) observeValueForKeyPath: (NSString *)keyPath ofObject: (id) object
change: (NSDictionary *) change context: (void *) context
{
//Set the label's text with new value.
}
Upvotes: 1
Reputation: 122381
You'll have to manage that yourself. If you look at the definition of the UILabel
text
property (link) you'll see that it copies the string contents, precisely for this very reason:
@property(nonatomic, copy) NSString *text
You could write a custom setter method for the aString
property:
- (void)setAString:(NSString *)aString
{
_aString = aString;
self.aLabel.text = aString;
}
(If you are following the current trend of letting clang
generate the backing instance variables and accessor methods for you, then you will probably need to explicitly declare this particular one, i.e. using an instance variable called _aString
).
Upvotes: 12
Reputation: 1716
You may want to use the mechanism better explained here:
Is there any data binding mechanism available for iOS?
The gist of it is there's no nice way to do it; there are, however, messy ways to do it using NSNotificationCenter and listening for specific changes.
UI bindings themselves don't exist on iOS (it was my biggest shock when converting from Mac OS X to iOS).
Upvotes: 0