2

I'm using a UIView. The application is using ARC. UIView is used in multiple view controllers. In UIView a listener to the UIKeyboardDidHideNotification is added. The listener works fine with some view controllers and with other view controllers it crashes the application. Especially when I use in the second view contoller after using in the first. The error is

* -[appname keyboardWillHide]: message sent to deallocated instance 0xb9c2760

In some scenarios the listener is getting called twice.

The code i have added in the uiview drawrect method is:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil];

the code for listener is

-(void)keyboardWillHide
{
    if(boolisViewlifted)
    {

            CGRect newFrame=self.frame;
            newFrame=CGRectMake(self.frame.origin.x, self.frame.origin.y+250, self.frame.size.width, self.frame.size.height);
            self.frame=newFrame;
            boolisViewlifted=false;

    }
}

The uiview appears on top of the calling view controller. Please let me know what causes this error and how to solve it.

Inder Kumar Rathore
  • 37,431
  • 14
  • 121
  • 176
user1531912
  • 355
  • 1
  • 4
  • 16

1 Answers1

1

Your view is getting unloaded because of memory warnings. You need to override dealloc method & remove observer for all notifications in all views where you added observer for notifications.

//do add in all views
-(void)dealloc
{
     //[super dealloc];//As you are using ARC don't call super's dealloc
     [[NSNotificationCenter defaultCenter] removeObserver:self];
} 
Rahul Wakade
  • 4,622
  • 2
  • 20
  • 25
  • Thanks.. it works now. But here i have a clarification-- im using ARC in my project, still why it is required to manually removeobserver in dealloc. – user1531912 Dec 08 '12 at 14:15
  • Adding observer for notification dosen't mean that some memory will be allocated for it which will be released automatically by ARC. Adding observer means you are registering your class(or object) for notifications and ARC dosen't deregister your class. You have to do it. – Rahul Wakade Dec 08 '12 at 14:27
  • See below links for clarification about where to remove observer- http://stackoverflow.com/questions/7827953/removing-observers-in-post-arc-cocoa http://stackoverflow.com/questions/7292119/custom-dealloc-using-arc-objective-c – Rahul Wakade Dec 08 '12 at 14:29
  • I was facing the exact same issue. Thanks Rahul for the help! – Joel Joseph Jul 10 '13 at 08:46