选择器未收到来自 NSNotificationCenter 的通知 (iOS)

Selector don't getting notification from NSNotificationCenter (iOS)

我正在使用 NSNotificationCenter 从 class 继承自 NSObject 发送通知。

通知应该发送给 2 个 viewController,但它只发送给其中一个。

我的代码:

fetchFromParse:

-(void)sendAllStores
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"getStoresArrays" object:nil userInfo:self.storesDict];
}

firstVC.m(工作):

- (void)viewDidLoad {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getStoresArrays:) name:@"getStoresArrays" object:nil];
}

-(void)getStoresArrays:(NSNotification*)notification
{
    NSLog(@“Working”); //Working   
}

secondVC.m(不工作):

-(void)prepareArrays
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getStoresArrays:) name:@"getStoresArrays" object:nil];
}
-(void)getStoresArrays:(NSNotification*)notification
{
    NSLog(@“Not Working”); //Not working
}

AppDelegate.m:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    secondVC *secVC=[[secondVC alloc] init];
    [secVC prepareArrays];

    fetchFromParse *fetchFromParseObj=[[fetchFromParse alloc] init];
    [fetchFromParseObj getStoresFromParse];

    Return YES;
}

注意:Xcode 向我显示一条错误消息 "firstVC is not registered as an observer"。

firstVC 从未使用过,因此无法添加观察者。

它在 viewDidLoad 中添加了观察者,但如果从未使用过视图控制器,则它无法加载视图,因此不会添加观察者。

据我所知,这里只应调用一个通知侦听器,它应该是您的 SecondVC,因为您的第一个视图控制器尚未加载,因此没有为第一个视图控制器注册观察者。

您的代码逻辑不正确。您正在发布一个通知,并让两个 class 成为观察者,因此这将导致不可预测的结果。您应该有一个 class 作为通知的观察员。