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?

Shardul
  • 4,266
  • 3
  • 32
  • 50
al03
  • 144
  • 1
  • 9
  • @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 '13 at 03:18
  • sorry, my bad,I don't learn good about Objective-c, I edited my question again, so please help me. – al03 May 19 '13 at 15:18

3 Answers3

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

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • @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 '13 at 05: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.
}
Amar
  • 13,202
  • 7
  • 53
  • 71
  • I edited my question again, please read it and give me the best way to solve it, thanks. – al03 May 19 '13 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).

Community
  • 1
  • 1
David Doyle
  • 1,716
  • 10
  • 23