Send a notification from AppDelegate to ViewController

前端 未结 2 1584
余生分开走
余生分开走 2021-01-16 20:25

need your help. I implement these Delegate Method to the AppDelegate.m:

    -(BOOL)application:(UIApplication *)application
           openURL:(NSURL *)url
          


        
相关标签:
2条回答
  • 2021-01-16 20:34

    you can use NSNotificationCenter as shown below:

    Firstly post Notification in your app delegate as :

    NSDictionary *_dictionary=[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%d",newIndex],nil] forKeys:[NSArray arrayWithObjects:SELECTED_INDEX,nil]];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:SELECT_INDEX_NOTIFICATION object:nil userInfo:_dictionary];
    

    then register the ViewController you want to observe this notification as

    /***** To register and unregister for notification on recieving messages *****/
    - (void)registerForNotifications
    {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(yourCustomMethod:)
                                                     name:SELECT_INDEX_NOTIFICATION object:nil];
    }
    
    /*** Your custom method called on notification ***/
    -(void)yourCustomMethod:(NSNotification*)_notification
    {
        [[self navigationController] popToRootViewControllerAnimated:YES];
        NSString *selectedIndex=[[_notification userInfo] objectForKey:SELECTED_INDEX];
        NSLog(@"selectedIndex  : %@",selectedIndex);
    
    }
    

    call this method in ViewDidLoad as :

    - (void)viewDidLoad
    {
    
        [self registerForNotifications];
    }
    

    and then on UnLoad remove this observer by calling this method :

    -(void)unregisterForNotifications
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:SELECT_INDEX_NOTIFICATION object:nil];
    }
    
    
    -(void)viewDidUnload
    {
        [self unregisterForNotifications];
    }
    

    Hope it helps you.

    0 讨论(0)
  • 2021-01-16 20:37

    You can post a local notification like this, where notification name will be used by the receiver to subscribe.

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

    And in your viewController subscribe the notification.

    [[NSNotificationCenter defaultCenter] 
        addObserver:self 
        selector:@selector(getData:) 
        notificationName:@"Data" 
        object:nil];
    
    - getData:(NSNotification *)notification {
        NSString *tappedIndex = [[_notification userInfo] objectForKey:@"KEY"];
    }
    

    For More About the NSNotificationCenter Can go with this link

    0 讨论(0)
提交回复
热议问题