Is it better to observe properties or redefine setters?

Say we have this interface CustomButton:

@interface CustomButton : UIButton
    @property (nonatomic, assign) CGFloat minWidth;
@end

With every change, minWidthwe want to place ours again CustomButton. As far as I know, we have two solutions:

Observed property value

// In -initWithFrame:
[self addObserver:self forKeyPath:@"minWidth" options:0 context:nil];

// In -observeValueForKeyPath:ofObject:change:context:
[self setNeedsLayout];

Override minWidthsetter

// In -setMinWidth:
_minWidth = minWidth; // Side note: it an ARC project
[self setNeedsLayout];

Which one is the right decision and why?

+5
source share
2 answers

I can think of 3 reasons to override the setter property, not the KVO property.

1: side effects may vary

, ( ) . , , . , KVO , ! " NSKVODeallocateBreak" , .

2:

" ", , , . KVO ( ) , . , , - . , .

3:

, KVO: , ,

-observeValueForKeyPath:ofObject:change:context:.

, , . , ?

+5

:

, minWidth , CustomButton.

, , . , , , . .

, , , .

"-", , ( ) , ( ) , .

, . , ( , ..).

0

All Articles