Aragunz
Aragunz

Reputation: 501

KVO in iOS in multiple classes and its context

Hi there I'm using KVO to observe AvPlayer states, i am using instances of AVPlayer in different controllers, and observing them usign KVO.(Ex home controller has player and its observers and category controller has player and its observers, etc). I have a centralized class of Constants where i put the obsever contests like :

static void const *kCurrentItemDidChangeKVO  = &kCurrentItemDidChangeKVO;
static void const *kRateDidChangeKVO         = &kRateDidChangeKVO;
static void const *kStatusDidChangeKVO       = &kStatusDidChangeKVO;

in each controller i add observers like:

 if (player != nil)
    {
        [player addObserver:self forKeyPath:@"rate"                            options:NSKeyValueObservingOptionNew context:&kRateDidChangeKVO];
        [player addObserver:self forKeyPath:@"currentItem.status"              options:NSKeyValueObservingOptionNew context:&kStatusDidChangeKVO];
        [player addObserver:self forKeyPath:@"currentItem.duration"            options:NSKeyValueObservingOptionNew context:&kDurationDidChangeKVO];
    }

and remove observers in each controller like:

if (player != nil)
    {
            [player  removeObserver:self forKeyPath:@"rate" context:&kRateDidChangeKVO];
            [player  removeObserver:self forKeyPath:@"currentItem.status" context:&kStatusDidChangeKVO];
            [player  removeObserver:self forKeyPath:@"currentItem.duration" context:&kDurationDidChangeKVO];
    }

and in each AVPlayer i add and remove observers when that class(ViewController) is viewed, visited, viewWillAppeard or viewWillDissapeared using same contexts from Constants file.

My Question is: It is fine using same contexts from a centralized Constants file for each class containing player observer or should each class have their own contexts unique for that class?.

Any help is very appreciated. Regards

Upvotes: 1

Views: 533

Answers (1)

Paresh Navadiya
Paresh Navadiya

Reputation: 38249

Best use : To create a global AVPlayer and its KVO and use in application as it would easy to manage in background and foreground state of application and easy to use.

Note : At a time only one sound/video can be played so even if its different for different view controllers then use same global AVPlayer to do so.

How it can be done ?

Use global AVPlayer's instance in different view controllers with simple rule is that remove AVPlayer's view added before using in different view controller where its being added again.

Bad pratice of usage : Creating a new AVPlayer and its KVO for each view controllers which will be difficult to handle.

Upvotes: 1

Related Questions