Search code examples
iosswiftreal-time-data

Realtime update in all UIVIewController


I have situation like this. Suppose VC A has some list of event which has like functionality When user click on any event they can redirect to it's details page where there is name of event organizer On click on of event organizer load it all event Now if i like one event of that organizer then it also reflect at VC A.

There are three ways I thoughts

1) I used NSNotificationCenter but it fire multiple time because same VC appear multiple time in cycle

2) Delegate chaining also not possible for this scenario

3) KVO also not compatible because in profile new api call happen

Currently i am using database for this but in ViewWillAppear there are lot's of code more management


Solution

  • You can use NSNotificationCenter!

    Every time in your ViewWillAppear do like,

       [[NSNotificationCenter defaultCenter] removeObserver:self name:@"EventChangeOfOrganizer" object:nil];
    
    
       [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(eventChangeOfOrganizer:)
                                                 name:@"EventChangeOfOrganizer"
                                               object:nil];
    

    and from your details screen where event change,

       dispatch_async(dispatch_get_main_queue(), ^{
    
                         [[NSNotificationCenter defaultCenter] postNotificationName:@"EventChangeOfOrganizer" object:nil];
    
                     });
    

    Swift :

    It should be something like below in swift,

        NSNotificationCenter.defaultCenter().removeObserver(self, name: "EventChangeOfOrganizer", object: nil)
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("eventChangeOfOrganizer:"), name:  "EventChangeOfOrganizer", object: nil)
    
        dispatch_async(dispatch_get_main_queue()) { 
    
            NSNotificationCenter.defaultCenter().postNotificationName( "EventChangeOfOrganizer", object: nil)
        }