解除后再出现自定义UIView控制器错误的NSNotificationCenter

时间:2013-10-25 08:55:37

标签: ios objective-c xcode

我有一个包含一些视图和自定义uiview的视图控制器。当我用手指触摸屏幕时,由于自定义uiview,我画了一条线。

为此,我将location.xlocation.y通过通知中心发送到我的自定义uiview

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];

在我的自定义uiview中,我以这种方式收到所有内容:

[[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);

,效果很好!!!但只是第一次!!!

问题是 如果我关闭我的自定义uiview初始化的主视图控制器并且我回来(例如再次播放)出现此错误

  

[__ NSCFType addLine:]:发送到实例的无法识别的选择器   0x1454dec0    * 由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [__ NSCFType addLine:]:   无法识别的选择器发送到实例0x1454dec0'

看来观察员在解雇后不再工作......你能帮助我吗?

感谢

3 个答案:

答案 0 :(得分:3)

您可能忘记删除dealloc中的观察者

- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

答案 1 :(得分:0)

我认为你应该这样试试。

-(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];

答案 2 :(得分:0)

在对象内部的postnotification方法中,你传递的是self,但是在添加观察者时,你传递的是nil。所以修改了以下方法: -

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