2012-07-27 38 views
0

您好我有一个奇怪的问题,NSNotificationCenter将无法运行选择方法

在我MainViewController I类职位时曾经按钮按下得到通知

[[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]; 
+1

当发送通知时,您确定Slide1ViewController在内存中吗? – dasdom 2012-07-27 11:26:08

+3

你在'Slide1ViewController'中实现了'step'方法吗? – trojanfoe 2012-07-27 11:27:24

+0

如何初始化您的Slide1ViewController对象?我猜你没有使用[Slide1ViewController alloc] initWithNibName:function。我想你只是使用init函数。你可以发布你分配“Slide1ViewController”的代码吗? – Srikanth 2012-07-27 11:27:46

回答

0

非常感谢@Phillip Mills您是对的我需要将它声明为MainViewController的@property现在它可以工作!非常感谢这个问题让我疯狂。

+0

删除并修改您的问题。 – trojanfoe 2012-07-27 11:57:25

+0

第一反应是你在“添加”之前“发布”:-) – cloosen 2012-07-27 12:36:16

0

你有发布通知之前注册两个观察者,所以你必须发布通知之前并初始化你Slide1viewcontroller在内存中。