multiple listeners for delegate iOS

前端 未结 3 1872
抹茶落季
抹茶落季 2021-02-14 10:20

I have a class search bar with a delegate didSelectString. I have an class A that implements the delegate and a class B that implements the delegate.

However only the de

3条回答
  •  清酒与你
    2021-02-14 10:51

    The delegation is a single messaging protocol. You'll need to use NSNotifications if you want to message multiple objects of a change.

    You can pass an object using notifications centre like so:

    NSDictionary *userInfo = @{@"myObject" : customObject};
    
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:@"myNotificationString" object:self userInfo:userInfo];
    

    When wanting to listen for notifications

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myCustomObserver:)name:@"myNotificationString" object:nil];
    

    And setting up the selector

    -(void)myCustomObserver:(NSNotification *)notification{
        CustomObject* customObject = notification.userInfo[@"myObject"];
    }
    

提交回复
热议问题