How to set value without KVO trigger

I use the following code to add KVO to an object.

[self.model addObserver:self forKeyPath:@"userName" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; 

Now I want to set userName as shown below. Yes, it will cause KVO.

 self.model.userName = @"testUser"; 

However, I want to set the value without a KVO trigger. How to do it? Is there a way like below that allows me to do this?

 [self.model setValue:@"testUser" forKey:@"userName" isSilent:YES]; 
+4
source share
2 answers

Core Data implements setPrimitiveValue:forKey: so you can do this. You can implement the same method in your object.

 [self.model setPrimitiveValue:@"testUser" forKey:@"userName"]; 

In this case, however, this should be in the context of notification aggregation, where the observer is eventually notified using the willChangeValueForKey: and didChangeValueForKey: .

+6
source

Your design is broken if you want to do it. A point of observation for key values ​​is what someone wants to know when a field changes, so they register for notifications. From a compliance point of view, compliance is that you keep your options open as to how the rest of the system interacts with you.

It seems that you are trying to crack some kind of problem when you do not want someone to know the true value of the property for some reason. Therefore, they think that they are receiving updates, but in fact, if they were to check the property, then it turns out that you were intentionally lying.

As expected, Cocoa does not have support mechanisms for such hacks. This is a very bad practice that violates the whole structure of object-oriented programming.

Distracted to the side, you can write a custom setter that went directly to the instance variable. For example,

 - (void)setUserNameAndLieAboutItAsAShortSightedHack:(NSString *)newName { _userName = newName; } 

At the system level, monitoring of key values ​​is carried out by creating a new version of the property settings tool that contains a call to a real setter and makes corresponding calls from observers from the outside. Therefore, avoid the real setter to avoid notifications.

+5
source

All Articles