为该类之外的类注册通知观察者

时间:2014-01-14 09:09:54

标签: ios objective-c nsnotificationcenter

我想在观察通知接收的班级之外注册一个通知观察员。

我尝试这样做:

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

但是,这迫使我将ViewController类中的NotificationReceived方法设为+(void)而不是-(void),就像我希望它一样

有没有办法将ViewController注册为ViewController类之外的通知观察者?

2 个答案:

答案 0 :(得分:2)

您必须创建该类的实例并将其保留在内存中,例如:

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

请记住在取消分配观察者之前取消注册观察者,否则您的应用将crash

或者在Swift 3中:

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

答案 1 :(得分:2)

发布通知:

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

在任何视图中添加观察者:

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