2014-01-14 42 views
1

我想在观察通知接收的课程之外注册通知观察员。为该课程以外的班级注册通知观察员

我试图做这样的:

[[NSNotificationCenter defaultCenter] 
     addObserver:[ViewController class] 
     selector:@selector(NotificationReceived:) 
     name:@"notification" object:nil]; 
然而

,这迫使我做出的ViewController类NotificationReceived方法是+(void)而不是-(void)像我想这是

有一种将ViewController注册为ViewController类之外的通知观察器的方法?

回答

2

你必须创建一个类的实例,并保持它活在内存中,这样的:

UIViewController *myViewController = [[UIViewController alloc] init]; 
[[NSNotificationCenter defaultCenter] addObserver:myViewController 
             selector:@selector(NotificationReceived:) 
              name:@"notification" 
              object:nil]; 

记住观察者被释放之前未注册的观察者,否则你的应用程序将crash

还是在斯威夫特3:

let myViewController = UIViewController() 
NotificationCenter.default.addObserver(
    myViewController, 
    selector: #selector(NotificationReceived), 
    name: Notification.Name("notification"), 
    object: nil) 
+0

但系统应该创建一个实例对我来说,因为它是一个视图 - 控制 –

+1

@LenaBru ???不,这个说法没有意义。没有什么特别的关于viewControllers,像所有其他类,你必须创建一个实例 –

+0

如果我在通知的注册创建实例,我没有收到通知.....在我需要在运行时的类 –

2

张贴通知:

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

对于任何视图添加观察:

// Add observer 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yourmethod) name:@"notificationName" object:nil];