Add and remove observer from multiple AVPlayerItem on UITableViewCell
<p>i am trying to make a table view that plays multiple videos with <code>AVPlayer</code> and <code>AVPlayerItem</code> and i needed to addObserver to each <code>AVPlayerItem</code> so i can keep track of playbackLikelyToKeepUp property</p>

<p>what i tried and failed is adding the observer after setting the <code>AVPlayerItem</code> and removing it in the <code>deinit</code> of the <code>UITableViewCell</code> but since the cells never gets deallocated but gets dequeued so this won't work and i will get this error </p>

<pre><code>An instance 0x14eedebc0 of class AVPlayerItem was 
deallocated while key value observers were still registered with it.
</code></pre>

<p>After searching I came up with this</p>

<ul>
<li>I should not add or remove observers on <code>UITableViewCell</code> but i had to because the player item is made in the cell subclass</li>
<li>The best way to handle observer is within 'UITableViewDelegate' methods </li>
<li>Adding in <code>willDisplayCell</code> and removing in <code>didEndDisplayingCell</code></li>
</ul>

<p>but even that does not work in my case because <code>AVPlayerItem</code> takes time to be initialized </p>

<pre><code>override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
        cell.setUpPLayer()
        return cell
}

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        let cell = cell as! TableViewCell
        if cell.Player == nil {
            self.addObserversToCell(cell)
        }
}

override func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        let cell = cell as! TableViewCell
        self.removeMyObserversFromCell(cell)
}
</code></pre>

<p>so the observer won't be add in the <code>willDisplayCell</code> but removing the observer will be called and will cause runtime error with </p>

<pre><code>'Cannot remove an observer &lt;AVFPlayer.TableViewCell 0x13cf1e9b0&gt; for
the key path "playbackLikelyToKeepUp"  
&lt;AVPlayerItem0x13cf31860&gt; because it is not registered as an observer.'
</code></pre>

<p>if anyone knows how to achieve this , I would be happy to know ? thanks</p>