Delegation in a NSThreaded Design? (iPhone) - iphone

Im using a large amount of very small web services in my app and I have been down a couple of roads that does not scale or work as desired.
The Design approach Im thinking about:
The task for the viewController is to ask for a set of data from a general webServicesClass, this task is started in a new NSThread -> this will instantiate an object which solely retrieves the xml and returns it to the webServicesClass -> the webServicesClass now instantiates an object which solely can Parse some XML coming from this particular web service. The Parser then returns a nice Entity object to the webServiceClass. The WebserviceClass now needs to inform the viewController about this data.
The viewController implements a webServiceClassDelegate and some delegate methods to see if the web service request went as planned. e.g. -(void)aWebserviceFailed and -(void)aWebserviceSuccess.
0.5 Since the WebserviceClass is running is a different NSThread, will it be a problem calling delegate methods on the main NSThread in the parent object?
1.0 I think this design is sound as it completely incapsulates the retrieval, parsing and returning of the Entity in different classes. But, I will have to write delegation methods and implement delegation protocols on each step of the way, for each different webservice. i.e. starting from the bottom, the WebserviceClass must implement delegation methods for both the object that retrieves the XML (start, fail, success), then for the object that parses the XML(start, fail, success) and the WebserviceClass must be able to delegate each of these responses to the viewController that again must implement delegation methods from the WebserviceClass(start, fail, success).
Is there a much simpler way to do this?
I have some design pattern experience, but not from languages that uses delegation so consistently as Objective C. In AS3 or Java I would have events that could bubble up through the objects and inform whoever was listening about changes. In all the Objective example code I have read I have only seen NSNotifications (which would be the equivalent of the AS3 or Java 'Event') used 0.1% of the times.
The Design I described will give me something that scales perfectly for many web services and gives me complete control over where a potential error/exception happens, but it seems to be a lot of code to obtain this loose coupling.
1.1 Or should I fully embrace the delegation approach and get to work:)
Thanks for any pointers or help given. Im not asking for source code or the likes, more a "this is considered best practice in Objective C in the every day situation you just described" :)

I'd recommend taking a look at ASIHttpRequest(obtainable here) and NSOperation + NSOperationQueue (docs here). I don't think you should run a long-lived thread to talk to your web service all the time, unless you absolutely need a constant connection.
Basically ASIHttpRequest and NSOperation both encapsulate all of the networking and threading stuff. Operations make multi-threading on the iPhone really nice. Essentially you create an operation (through a factory or whatnot for ease of use), pop it in a queue and do something with the result.
As for what you do with the result (this applies to your original scenario too and 0.5 and 1.1) what typically happens is your operation/thread will then call a didSucceedAtGettingWhatever or didFailWithError:(NSError*) method. Delegation is pretty much the defacto way of making requests on the phone. If there are multiple delegates, then you can just use subject-observer, like you would in Java.
As for 1.0, ultimately no. What we typically do is we have an OperationDelegate and OperationTypes. Based upon which OperationType succeeded or completed, we have different logic. It's not the greatest and there are a ton of different ways of doing this, but you will have to have separate logic for separate events regardless of what you do. Whether or not that's in one method or many methods is up to you.

Related

Running continuos thread in app delegate is proper or not

In my app requirement is, when the app is launch for the first time it will send request to server to get data, parse it and save it in document folder which will be used across entire project.Again after particular time interval the app will send request to server to get updated data(if any) and update that data in document folder, which again will be updated across entire project.All this process is happening in background thread.This process will repeat until the app is running in foreground once the user close the app, the app will get terminate, it will not go in background.
This repeated request I am creating in app delegate as well as doing xml parsing once the data is received and saving after parsing. Now my question is, Is this proper means doing too much stuff in app delegate is safe or there is some limitation or is this bad programming?
What is the correct way of doing this?
I disagree with torrey.lyons to an extent. I think creating singletons is bad practice generally speaking and should be avoided where possible. One thing you should never do is code a class so that it has to be a singleton. Purpose built singletons tend to increase coupling and can be really problematic when it comes to unit testing where you might want to replace your singleton with a stub class or you might need it to be reinitialised for each unit test.
If this task of getting data is an application level task, there is absolutely no reason why it can't logically be located in the application delegate. I would however create a "connection manager" as torrey.lyons suggests and have one as a property of the app delegate.
I would also not use an explicit background thread to do the data update but I would use a subclass of NSOperation. This is a whole lot easier than managing your own thread.
It is bad practice. Your app delegate should ideally be concerned purely with its own responsibilities, i.e.. responding to the messages the application sends its delegate. It is much better to split off other discrete responsibilities into other objects. For example, you could have a "connection manager" object that is responsible for periodically communicating with the server. If you are sure the app will only connect to one server at a time you probably want to use the singleton pattern so that there only one instance of the object in your application and it can be easily reached by any other class. A good discussion of the proper role of the app delegate and singletons can be found on at Singletons, AppDelegates and top-level data. A good general overview on writing singletons can be found under the Care and Feeding of Singletons.

iOS/Objective-C Multiple URL Connections

I have a few apps that I am trying to develop a reusable URL connection layer. I have done some research and am struggling between architectures. Specifically the APIs this layer utilizes.
In the past, I have used NSURLConnection and NSOperation on a separate RunLoop. This seems overkill. I've seen libraries that subclass NSURLConnection. Others have a singleton Engine object that manages all requests.
The Engine and/or NSURLConnection seem best to me. But I am asking for input before I go too far down one road. My goals would be:
Ability to cancel a request
Concurrent requests
Non-blocking
Data object of current open requests
Any direction or existing references with code samples would be greatly appreciated.
I'm not sure about a "data object of current open requests", but ASIHTTPRequest does the first three and is very easy to use.
Update
Actually, it looks like ASINetworkQueue may fulfill your last bullet point.
I personally use a singleton engine with my large Apps though it might not always be the best case. All the URL's I use require signing in first, figured it would be best if one Class handles all of the requests to prevent multiple URLS from signing into the one location.
I basically create a protocol for all my different connection classes into my singleton and pass the delegate of both the calling class and the singleton into it. If an error occurs its passed to the singleton so it can deal with it, if it completes it returns the data to the calling class.

Pros and Cons of Listener/Observer approaches to notify Model changes

In any typical iPhone application, there will be model classes that are responsible for data loading/parsing. Upon completion of the data loading/parsing tasks, the affected controllers needed to be notified of the change in the model and update the view accordingly.
There are several listener/observer approaches for this in iPhone application development. What are the pros/cons and reasons for using each of the following approaches?
KVO
NSNotification
Delegate
Any other known approach
In my own experience:
Delegation:
PRO: use only when you have a single object to notify;
PRO: using an explicit protocol you can document clearly your intentions;
CON: can be the source of crashes and memory leaks if wrongly used (tip: don't retain delegates, assign them, and remember to deassign delegates when / if they are released!)
I wrote about memory management problems generated by delegation in this article on my blog:
http://akosma.com/2009/01/28/10-iphone-memory-management-tips/
NSNotification:
PRO: better when you have several objects to notify;
PRO: very flexible, leads to loosely-coupled classes;
CON: notifications are sent synchronously (so make sure your individual notification handlers only do very little)
CON: sometimes hard to document and maintain. Be sure to clearly explain in header docs what each notification means and when it is sent.
KVO:
Similar concerns about NSNotifications;
CON: even more obscure to document. Be sure to add more header docs or architectural tips on your comments to explain who's listening what. I personally wouldn't use KVO for data loading or parsing tasks.
Personally, when dealing with network-enabled apps talking to a remote web service, I use a singleton data loader class (wrapping ASIHTTPRequest and handling all the serialization and deserialization) which pops notifications when something occurs. This way I can have the app delegate handling connection errors on its own (popping up alerts and such if required), and each controller only cares about the responses it wants.
Of course, this approach depends on the application, but this general architecture might be a starting point for your own code.

iphone RESTful webservices

Not even sure if the title is correct, however, what I'm trying to do is use the standard NSURLConnection class to handle responses from calling my webservice. I am using the POST method to update a database and the GET method to retrieve rows from the database. The problem I have is that these 2 actions may occur simultaneously so that the methods to handle the request may step on each other. In other words in my "connection didReceiveData" method I have 2 paths through the code depending on whether I'm handling a response from a GET or POST request.
I keep track on which request in being processed by an instance variable called requestType. The problem is that since the requests are being executed simultaneously the instance variable is being changed from GET to POST before the GET completes (or vice-versa). My question is how do I maintain 2 separate requests in this scenario? Do I synchronize the requests? Is there a way for threads to work here? Do I create 2 separate objects for each of the requests and have the logic in "didRecieveData" query for which object is being processed? Any help would be much appreciated!!
Dealt with a similar issue in one of our apps. The solution involved creating a class that represents a webservice call, responsible for calling its own url, loading its own data, etc. The call class had a delegate that would handle parsing the responses (in our case, a web service controller). Wound up getting rather complicated, but prevented the issue of NSURLConnections stepping on each other.
Seems like you've created a messy problem by having a class that tries to do too many things. I would suggest taking one of the following three approaches:
1) Write two classes, one for updates and one for retrievals. Each class creates it's own private NSURLConnection object and acts as the delegate for the async notifications received from the NSURLConnection. The classes could possible share some utility parsing code or extend a base object that has that parsing code in it. But the key being that the code calling these classes would instantiate one of them, make the call, and then release it. This will keep your code cleaner and will insure that the event notifications don't get intermingled.
2) Create a single class that, depending on initialization, does either a post or a get with it's own private instance of NSURLConnection. When a call needs to be made, instantiate the class, get the results, and then release the class.
3) Write your connection handling classes so they use the synchronous NSURLConnection method and call that call that class in a background thread.
Either way, clean code and clear object orientation will prevent messy scenarios like the one you're describing.
Create separate objects that handle the calls. If you want to issue multiple requests at once I would strongly recommend looking at NSOperationQueue, and making these objects subclasses of NSOperation... much nicer way to deal with multiple background requests.
A good example is here:
http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/
The idea there is that you use the non-asyncronous web calls, in operations that are run on separate threads. You can still use asynch calls in NSOperation as well, but doing so is a little trickier and for simple calls you probably do not need to.

Online play possibilities for iPhone game?

How would you guys go about creating online play capabilities for an iPhone game? Obviously, one could poll the server every so often, but is this realistic given the capabilities of the device? Assume you're polling the server every second or two and retrieving 100 bytes of data... Is it possible to retrieve the data in the background while gameplay continues or is it going to be held up by the server poll?
Thanks in advance,
BCH
You need to make a multithreaded application. Then you can have a background thread polling the server (or better, making asynchronous requests on it.
Have a look at the NSOperation and NSOperationQueue classes. You'll make each background task be represented by an instance of an NSOperation class. This class takes care of starting the operations, making sure that they are run in the appropriate order, and accounting for any priorities that you set.
The most common way to use NSOperation is to write a custom subclass and override the method, main. The main method gets called to perform the operation when the NSOperationQueue schedules it to run.
If you don't want the overhead of subclassing, take a look at the NSInvocationOperation class. This is a concrete subclass of NSOperation that makes it easy to attach an operation to an existing method. NSInvocationOperation objects can be added to an NSOperationQueue (just like NSOperations), so that you get multi-threading without having to subclass.
You can do asynchromous requests. But you are asking a really, really hard question here. Just want to make sure you know that.
Take a look at the WiTap example (in xcode do a full text search for witap). It uses NSStreams to get asynchronous behavior without you having to resort to managing your own threads or poll.
Use OpenFeint.. It allows you to develop Over the internet worldwide non real time turn based multiplayer games easily..
I'm not sure if GameCenter now supports similar functions.