1
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?

2
  • @fansEagle you've been given some great answers and instead of learning from them you argue against them. Did you want help or not? If so, listen and learn.
    – matt
    May 17, 2013 at 3:18
  • sorry, my bad,I don't learn good about Objective-c, I edited my question again, so please help me.
    – al03
    May 19, 2013 at 15:18

3 Answers 3

12

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).

1
  • @fansEagle Your question states that both aString and aLabel are in the same class. If that's not the case then you need to edit your question.
    – trojanfoe
    May 17, 2013 at 5:42
1

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.
}
1
  • I edited my question again, please read it and give me the best way to solve it, thanks.
    – al03
    May 19, 2013 at 15:22
0

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.