0

我有一个带有一些视图和自定义的视图控制器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”

似乎观察者在解雇后不再工作......你能帮我吗?

谢谢

4

3 回答 3

3

您可能忘记删除 dealloc 中的 oberver

- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}
于 2013-10-25T08:59:02.767 回答
0

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

    [[NSNotificationCenter defaultCenter] addObserver:self 
selector:@selector(addLine:) name:@"addLine" object:self];
于 2013-10-25T10:22:26.390 回答
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];
于 2013-10-25T09:11:39.203 回答