Search code examples
iosobjective-ckey-value-observingdealloc

Need to call removeObserver twice


I have a view that observe values of itself on init like this :

[self addObserver:self forKeyPath:@"focusPointOfInterestIndicator" options:0 context:kSRCameraViewObserverContext];
[self addObserver:self forKeyPath:@"exposurePointOfInterestIndicator" options:0 context:kSRCameraViewObserverContext];
[self addObserver:self forKeyPath:@"paused" options:0 context:kSRCameraViewObserverContext];
[self addObserver:self forKeyPath:@"previewLayerGravity" options:0 context:kSRCameraViewObserverContext];

And on dealloc, observers are removed as they should be like this :

[self removeObserver:self forKeyPath:@"focusPointOfInterestIndicator"];
[self removeObserver:self forKeyPath:@"exposurePointOfInterestIndicator"];
[self removeObserver:self forKeyPath:@"paused"];
[self removeObserver:self forKeyPath:@"previewLayerGravity"];

But unless calling it twice (with or without context, doesn't change anything), I have a crash when the view is deallocated cause the value are still observed. But I'm quite sure observers are added only once (since it's in init of object).

I just wonder if why it could be registered twice ? Or is it like by calling it twice, it let to the object to effectively remove observers ? If someone have any clue ?


Solution

  • init is the primary initializer of NSObjet that means init must be called in Apple's implementation of initWithCoder / initWithFrame with something like [super init];

    so your sharedSetup is called twice

    EDIT (thanks to And Ainu):

    To be more specific, that's the init method of UIView which calls the initWithFrame method.