How to add observer on NSMutableArray?

前端 未结 3 2126
天命终不由人
天命终不由人 2020-12-24 04:44

I have searched a lot but didn\'t find useful code or tutorial.

In my application, I have an mutable array which update in every 60 seconds.

The objects in a

3条回答
  •  悲&欢浪女
    2020-12-24 05:04

    If you want to use shiny blocks you can do this

    // Create an instance variable for your block holder in your interface extension
    @property (strong) id notificationHolder;
    
    // Listen for notification events (In your TableView class.
    self.notificationHolder = [[NSNotificationCenter defaultCenter] addObserverForName:@"NotificationName"
                                 object:nil
                                  queue:[NSOperationQueue mainQueue]
                             usingBlock:^(NSNotification *note) {
    
            NSLog(@"Received notification");
    }];
    

    Then in dealloc (or when you don't use it anymore)

    - (void)dealloc {
         [[NSNotificationCenter defaultCenter] removeObserver:self.notificationHolder];
    }
    

    Then in some other class

    // Send a notification
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationName" object:nil];
    

    Ask if something is not clear! Hope it helps!

    EDIT DUE TO COMMENT

    The "YourEvent" is the name of the notification, this means that you can name it to whatever you want. (Perhaps "UpdateArrayNotification could be a good name?)

    Something to think about: Note that you can have several observers for the same notification. This means that one 'post' will be snapped up by all observers.

提交回复
热议问题