【问题标题】:IOS NSNotificationCenter addObserver from subclass of NSObjectIOS NSNotificationCenter addObserver 来自 NSObject 的子类
【发布时间】:2015-10-01 10:14:05
【问题描述】:

我从AppDelegate 添加了一个观察者,并将这段代码放入didFinishLaunchingWithOptiong 方法中。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
internetReachability = [Reachability reachabilityForInternetConnection];
[internetReachability startNotifier];

现在我想把这个addObserver 放在我的自定义类中,它是NSObject 的子类?

编辑:

这是我的reachabilityChanged 方法:

- (void) reachabilityChanged:(NSNotification *)note
{
    NSLog(@"change");
}

我将此方法放在调用 addObserver 的同一个类中

【问题讨论】:

  • reachabilityChanged 方法如果我把它放在 NSObject @Rage 的那个子类上,就不会被命中
  • reachabilityChanged: 选择器在哪里定义?在 AppDelegate 中?
  • 还有什么参数?如果你提供它的定义会更好。
  • 您需要确保几件事 - 1) 您正在从您的自定义类调用 startNotifier 方法并且代码正在执行。 2) 只要​​预计会有通知,您的自定义对象就一直存在。通常,单例对象在您的上下文中是有意义的。

标签: ios objective-c nsnotificationcenter nsnotifications


【解决方案1】:

为了运行reachabilityChanged方法,您需要将您在AppDelegate注册的通知发布如下

[[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification object:nil];

【讨论】:

    猜你喜欢
    • 2012-12-07
    • 2014-11-22
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    相关资源
    最近更新 更多