The difference between self.variable and _variable, about KVO

the first image uses self.name to change, and the second image using _name for change.it should be the same result, but the second displays nothing.why?

enter image description here

enter image description here

here is the code

#import "ViewController.h" @interface kvo : NSObject @property (nonatomic,strong) NSString *name; @end @implementation kvo - (void)change { _name = @"b"; } @end @interface ViewController () @property (nonatomic, strong) kvo *a1; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.a1 = [[kvo alloc] init]; _a1.name = @"a"; [self.a1 addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil]; [_a1 change]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { NSLog(@"1"); } 

difference self.name and _name in change method

Edit: this is not the same question as β€œWhat is the difference between _variable and self.variable in Objective-C? [Duplicate]”, I know this about the getter method and setter method, and my question is why the setter method fires KVO. and _name = @"b" does not start KVO.

+6
source share
2 answers

You will receive a KVO notification only when accessing an instance variable through a property. Direct setup of an instance variable will not trigger a KVO notification.

In the first case, you set the name

 self.name = @"b"; 

In fact, this will call the setName: property setting method, which internally sends KVO didChangeValueForKey notifications. In fact, notifications are called by calling the setter method.

In the second case

 _name = @"b"; 

You directly set the instance variable without the set setter method. Therefore, the KVO notification will not start.

If you want, you can run the notification yourself

 [self willChangeValueForKey:@"name"]; _name = @"b"; [self didChangeValueForKey:@"name"]; 

But I do not think it requires, set the variable using the property. This will do everything for you.
Read more about KVO Notice

+5
source

There are three things you need to get notifications about key values ​​for a property:

Step 1: The observed class must comply with the key value for the property that you want to observe.

Step 2: You must register the addObserver:forKeyPath:options:context: with the observed object using the addObserver:forKeyPath:options:context: method.

Step 3: The observation class must implement observeValueForKeyPath:ofObject:change:context:

Apple developer

0
source

Source: https://habr.com/ru/post/985834/


All Articles