XPC Service and NSTableView

Populating a NSTableView with a large amount of internet images isn’t a new problem. It may sound trivial and straight, but I see many programmers didn’t really solve it correctly. This article will introduce the correct structure for this problem and also make it as a XPC service. As the Apple document state, the two main reasons to use XPC services are privilege separation and stability. Since accessing a network resource can be slow and unstable, the XPC service is perfect for this job.

The main problem is that when the table view scrolling, these download threads will accumulate easily.  Thread accumulating is a bad thing, because, this will lead either OS X thread limit exceeded error or socket limit exceeded error. So, we have to have a structure to keep those threads in a queue and make them cancellable when a table view cell scroll out of the visible area. Keep this point in mind, here we have a list:

  1. the download code must be on background thread.
  2. there should be a queue to limit concurrent download thread number.
  3. the download code must be in an asynchronous fashion.

The point 1 is obvious. so the download code will not block UI action. The point 2 is used to solve the network overload issue.  The point 3 can make the download thread cancellable.

Here is the implementation of this structure.

XPCImageFetcher

This demo shows a NSTableview with 5000 rows. When a cell scroll into the visible area, UI App will send a request to a XPC service to download the image. Images will be resized inside XPC service and sent back to UI App and rendered on UI thread. If the cell scroll out of visible area before the download finished, then the UI App will send a cancel request to XPC service to stop the download thread.

This structure will make the App responsive and stable. Even the XPC is crashed, our UI App will remain running.

https://github.com/keefo/XPCImageFetcher

xpcscreenshot

screenshot