Be careful about object ownership around NSOperation and NSOperationQueue

For recent years, Apple people concentrated more on iOS than Mac OS X.
So, during that period of time, I’ve noticed that the quality of SDK for OS X and its documentation got worse.

In the case of NSOperation and NSOperationQueue, actually it was announced before the iOS was announced as far as I remember.
However, at that time, they were implemented around pthread or NSThread to provide eaiser pattern for multithreaded programming under specific scenario. ( Although those serial and pipe-like working model is quite convenient in many circumstances, but not always still. If you need more sophisticated interaction among threads, etc, you still need implementation with pthread/NSThread. )

Here is one example.
Were they clear about object ownership for NSOperation ( and its child classes ) when it’s added into a queue?
For tasks like it’s just queued and quickly consumed and gone, it will not easy to catch a case where an instance of a concrete children classes of NSOperation is deallocated while it’s in a queue and being processed.

However, today I did noticed such a case. So, be careful about this thing.
Making a pattern around something looks cool. It may show yourself a very skillful developer. By glancing at that kind of code, people can think of you as such.
However, it’s only skin-deep.

OperationQueue, Operation and ownership

ADDED : According to the document of NSOperationQueue, it says for addOperation:

Parameters
operation
The operation object to be added to the queue. In memory-managed applications, this object is retained by the operation queue. In garbage-collected applications, the queue strongly references the operation object.

So, at least it’s said to retain the operation. But be careful about it.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: