From 32fc629c334bf54744a9bde7fd5c70d70d3de5a7 Mon Sep 17 00:00:00 2001 From: Randall Luecke Date: Thu, 17 Mar 2011 01:31:25 -0400 Subject: [PATCH] Prevent memory leak my only adding the observer when the searchfield is added to a superview, that way we can also remove the observer later. --- AppKit/CPSearchField.j | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/AppKit/CPSearchField.j b/AppKit/CPSearchField.j index 0b4f89a23..58d67ec02 100644 --- a/AppKit/CPSearchField.j +++ b/AppKit/CPSearchField.j @@ -111,7 +111,7 @@ var RECENT_SEARCH_PREFIX = @" "; [self setEditable:YES]; [self setContinuous:YES]; - [[CPNotificationCenter defaultCenter] addObserver:self selector:@selector(_searchFieldTextDidChange:) name:CPControlTextDidChangeNotification object:self]; + var bounds = [self bounds], cancelButton = [[CPButton alloc] initWithFrame:[self cancelButtonRectForBounds:bounds]], @@ -126,6 +126,18 @@ var RECENT_SEARCH_PREFIX = @" "; _canResignFirstResponder = YES; } +- (void)viewWillMoveToSuperview:(CPView)aView +{ + [super viewWillMoveToSuperview:aView]; + + // In order to prevent a memory leak we add the observer here instead of _init, since it doesn't hurt to add it more than once + // but more importantly we remove it if the view is removed from the superview. + if (aView) + [[CPNotificationCenter defaultCenter] addObserver:self selector:@selector(_searchFieldTextDidChange:) name:CPControlTextDidChangeNotification object:self]; + else + [[CPNotificationCenter defaultCenter] removeObserver:self name:CPControlTextDidChangeNotification object:self]; +} + // Managing Buttons /*! Sets the button used to display the search-button image