NSNotificationCenter in custom UIView controller e

2019-09-07 20:14发布

问题:

I have a view controller with some views and a custom uiview. When I touch the screen with my finger I draw a line thanks to the custom uiview.

To do that I send location.x and location.y through Notification Center to my custom uiview like that

CGPoint location = [touch locationInView:self.view];
userInfo = [NSMutableDictionary dictionary];
[userInfo setObject:[NSNumber numberWithFloat:location.x] forKey:@"x"];
[userInfo setObject:[NSNumber numberWithFloat:location.y] forKey:@"y"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"addLine" object:self userInfo:userInfo];

And in my custom uiview I receive all in this way:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addLine:) name:@"addLine" object:nil];
NSDictionary* userInfo = notification.userInfo;
float x = [[userInfo objectForKey:@"x"] floatValue];
float y = [[userInfo objectForKey:@"y"] floatValue];
p = CGPointMake(x,y);

and it works well!!! But just the first time!!!

The problem is If I dismiss the main viewcontroller where my custom uiview is initialized and I come back (to play again for example) this error appears

[__NSCFType addLine:]: unrecognized selector sent to instance 0x1454dec0 * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType addLine:]: unrecognized selector sent to instance 0x1454dec0'

It seems that the observer doesn't work again after a dismiss...can you help me?

thanks

回答1:

You have probably forgot to remove the oberver in the dealloc

- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}


回答2:

In your postnotification method inside object you are passing self but while adding observer, inside that object you are passing nil. So modified the below method like that:-

    [[NSNotificationCenter defaultCenter] addObserver:self 
selector:@selector(addLine:) name:@"addLine" object:self];


回答3:

I think you should try this way.

-(void)viewDidLoad
{
//....YOUR_CODE....
//Add Observer
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addLine:) name:@"addLine" object:nil];
}

//Implement method for the notification
-(void)addLine:(NSNotification *)notification
{
NSDictionary* userInfo = notification.userInfo;
float x = [[userInfo objectForKey:@"x"] floatValue];
float y = [[userInfo objectForKey:@"y"] floatValue];
p = CGPointMake(x,y);
}

//and implement dealloc or viewDidDisappear or viewDidUnload method to remove observer.
- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"addLine" object:nil];    
}

//In Your Custom view or view controller, post notification as below..
[[NSNotificationCenter defaultCenter] postNotificationName:@"addLine" object:self userInfo:userInfo];