I am creating an iPhone application which communicates A LOT with my webserver. Communication is done using JSON. Now I was wondering what is the best way to handle this. I am currently starting my 3rd try to get this code the best I can, but I am still not completely sure.
For my first try, I tried setting up a normal class with a normal delegate property (used to tell the class where the call-backs should go to, once the request is done). This method kind of failed, because of the trouble of instantiating the class, setting the delegate (object responsible for the call-backs), calling the method and then cleaning it up again. Sometimes methods of the class need to be chained, to get all the data I need for certain pages within my app, and re-instantiating the class lead to a lot of memory problems and re-using the object (service) in the chaining event, made me supply a reference to the current object to all my call-back methods… Let me say, this was not ideal.
My 2nd try was making the class a Singleton, where for each method I specified which delegate should receive the call-back calls. This caused a couple of nasty code changes (as storing the delegate object somewhere, which could be retrieved, once the request is done). Chaining methods was a lot easier when using the Singleton, but somehow I get the feeling that I am completely abusing this.
The class has about 25 to 35 methods, which can have 2 outcomes: It either worked or it failed (with a specific errorcode and message). So we are talking about 25 – 35 * 2 callback methods that need to be called.
So I am not asking for any code examples, but I was wondering if people could give me some new insights on how to solve this.
I don’t know if it’s perfect, but maybe I can help you by telling how I do communication with Twitter. Basically there are a few classes doing all of this, but I’ll summarize it as if there’s only one class.
Basically the class gets instantiated and autorelease is immediately called. It gets a delegate assigned and it makes the request. This whole process takes 3 lines of code plus one line of code for every POST parameter or GET query parameter. Authenticating with OAuth also takes one line (
[request setAuthenticator:[MyNameOAuthAuthenticator authenticatorWithCredentials:...]]).The moment
-[req execute]is called, it calls[self retain]to compensate for the autorelease. When the request itself is done (or errored), the delegate is informed with the JSON object, and[self release]is called. This takes care of all memory issues.My code is currently built in a way where it only needs a minimum of one (!) line to execute:
[[[[MyRequest alloc] initWithHTTPMethod:httpMethodGET andURL:[NSURL URLWithString:...]] autorelease] execute]Maybe this helps 🙂