Setter Response

What is the best way to respond to data changes when calling properties. For example, if I have a property called data , how can I react when [object setData:newData] and still uses the synthesized setter. Instinctively, I would override the synthesized setter as follows:

 - (void)setData:(DataObject *)newData { // defer to synthesised setter [super setData:newData]; // react to new data ... } 

... but of course that doesn't make sense - I can't use super like this. So what is the best way to handle this situation? Should I use KVO? Or something else?

+4
source share
3 answers

There are several different ways to do this, depending on what kind of control you want. One way to do this is to monitor your property:

 [self addObserver:self forKeyPath:@"data" options:0 context:nil]; - (void)observeValueForKeyPath:(NSString *)path ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if(object == self && [path isEqualToString:@"data"]) { //handle change here } else [super observeValueForKeyPath:path ofObject:object change:change context:context]; } 

Make sure you remove yourself as an observer in your dealloc or finalize method, if not earlier.

Another way is to override -didChangeValueForKey: However, this method cannot be called if there are no observers at the facility.

 - (void)didChangeValueForKey:(NSString *)key { [super didChangeValueForKey:key]; if([key isEqualToString:@"data"]) { //handle change here } } 
+4
source

@synthesize creates default access devices for ease of use. If you need some special action, you can always write your own accessors instead of using @synthesize. The installer and receiver are not inherited from the base class, they are created by the @synthesize directive. Therefore, you do not need (nor can you) call super setData: (unless you really created a superclass that supports this).

Just make sure that you are managing memory correctly. The memory programming guide contains examples of how to manage memory for different types of memory policies (save, assign, or copy).

+2
source

From this answer SO .

You can define the synthesized property "private" (put this in your .m file)

 @interface ClassName () // Declared properties in order to use compiler-generated getters and setters @property (nonatomic, strong <or whatever>) NSObject *privateSomeObject; @end 

and then manually define the getter and setter in the "public" part of ClassName ( .h and @implementation part), like this,

 - (void) setSomeObject:(NSObject *)someObject { self.privateSomeObject = someObject; // ... Additional custom code ... } - (NSArray *) someObject { return self.privateSomeObject; } 

Now you can access the someObject "property, as usual, for example. object.someObject . You also get the advantage of automatically generated retain / release / copy , compatibility with ARC and almost no loss of thread safety.

0
source

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


All Articles