Follow LostMuser on Twitter

Monday, January 24, 2011

[iOS] Finish Later Queue

Often, in the course of making iPhone apps, you need to performs tasks that can finish later. Even after the window or controller that started the action gets closed and goes out of commission.

One approach, commonly done, is to retain your delegates. Since the controller is the delegate of the given action it will be kept around until the action is completed.

This leaky approach is fine and dandy until your app starts to get more professional. One day you'll get blindsided by circular retains (via delegates) and uncontrollable memory leaks.

In fact, apple would appear to have fallen for this same caveat. Some, presumably earlier, classes retain their delegates. *cough*NSURLConnection*cough* Meanwhile the newer classes never retain their delegates.

What is the solution? Use a FinishLaterQueue. The FLQ promises to take good care of your action, even after you're gone. Think of it as a rapture pet care service for your actions.

There are two steps. Make your class subscribe to the "FinishLaterQueueProtocol".


@interface MyNSURLWrapper : NSObject {
}

...

@end


It will need to store a (non-retained) pointer to FinishLaterQueue which it gets in the joinedFinishLaterQueue call. Check the protocol for info on this.

Do this when you need to use it:


MyNSURLWrapper *con = ....;

[[FinishLaterQueue shared] addObject:con];


Than have MyNSURLWrapper call 'reportObjectFinished' on the FinishLaterQueue when it's done, so it can get released then.

FinishLaterQueue.zip

Download it above.

0 comments:

Post a Comment

Musing's Blog Viewer Webcam



(People reading the blog right now!)