Search code examples
objective-ciosxcodegrand-central-dispatchkey-value-observing

Grand Central Dispatch (GCD) + Key-Value Observing (KVO)


I have a method in which I add observers:

- (void) method
{
    [currentPlayer addObserver:self forKeyPath:@"some" options:some context:some];
}

All the changes are processed in these method:

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

If I modify my method to:

- (void) method
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [currentPlayer addObserver:self forKeyPath:@"some" options:some context:some];
    });
}

Does it mean that - (void) observeValueForKeyPath... will work in DISPATCH_QUEUE_PRIORITY_HIGH?

P.S. I want KVO to work in DISPATCH_QUEUE_PRIORITY_HIGH.

EDIT:

I observe AVPlayer variables. Such as:

[currentPlayer addObserver:self forKeyPath:@"currentItem.loadedTimeRanges" options:NSKeyValueObservingOptionNew context:kTimeRangesKVO];

These variables are changed automatically.

Every time "observeValueForKeyPath" is called I check the queue and it remains dispatch_get_main_queue() and I don't know how to change it to some other queue.


Solution

  • As an observer you can't control what thread / queue observeValueForKeyPath is called from. You could wrap a dispatch onto the queue you wish around the work this method doing. That will move the work of the observation to the high priority queue.

    Just be sure you're aware this work is likely to be running on a different thread / queue than the code that triggered the observation. If the object you're observing is not thread safe you will need to inspect it prior dispatching the rest of the work onto a different queue.