0

嗨,我有一个奇怪的问题,

在我的MainViewController类中,我会在按下按钮时发布通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"step" object:nil];

在我自己的课堂上,我有一个观察员

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

运行“step”方法

- (void)step {
    NSLog(@"works");
}

在另一个名为Slide1ViewController的类中,我也有一个观察者

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        NSLog(@"works 2");

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(step) name:@"step" object:nil];
    }
    return self;
}

并且 dealloc 方法将其删除

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"step" object:nil];
}

在 MainViewController 中,该方法被调用,但在 Slide1ViewController 中永远不会。

Slide1ViewController 像这样初始化:

Slide1ViewController*test = [[Slide1ViewController alloc] initWithNibName:@"Slide1ViewController" bundle:nil];
test.view.frame = CGRectMake(1024*0, 0, 1024, 768);
[contentScrollView addSubview:test.view]; 
4

2 回答 2

0

您必须在发布通知之前注册您的两个观察者,因此您必须在发布通知之前在内存中初始化 Slide1viewcontroller。

于 2012-07-27T11:46:27.600 回答
0

非常感谢@Phillip Mills,你说得对,我需要将它声明为 MainViewController 的 @property 现在它可以工作了!!!非常感谢这个问题让我发疯。

于 2012-07-27T11:50:26.867 回答