Search code examples
iphonekeyboarddeallocdismiss

Dismissing Keyboard and dealloc()


Got one here which is causing 'concern'...

I have a modal view controller which uses the keyboard. I am using a system to dismiss the keyboard from code on stackoverflow which appear to be the 'new way' of recognising taps outside the keyboard to dismiss it...

// Register for keyboard dismissal
[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification object:nil queue:nil usingBlock:^(NSNotification *notification) 
{
     UITapGestureRecognizer *tap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)]autorelease];
     tap.numberOfTapsRequired = 1;
     tap.numberOfTouchesRequired = 1;
     tap.delegate = self;
     [self.view addGestureRecognizer:tap];
}];

[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification object:nil queue:nil usingBlock:^(NSNotification *notification) 
{
    [self.view removeGestureRecognizer:[self.view.gestureRecognizers lastObject]];
}];

This works well but I notice that dealloc is not being called on my view conroller when I dismiss it via a Done button.

It seems to be something to do with the code above. If I comment out the executable code within the notification definition braces, then dealloc is called ok when the controller is dismissed....(keyboard has not been shown or dismissed, so code within braces has not executed)

Has anyone got any suggestions as to why dealloc is not being called when above code is implemented?

Thanks

Fitto


Solution

  • While using block it will retain "self", so you need to remove observer to dealloc.