I am developing an iPhone application in which I need to use Facebook’s FQL to load the user’s notifications. As I need to load these notifications different places in the application I would like to make a subclass of NSObject to load and return these notifications as an array.
I understand that I should make a subclass (NotificationLoader) and then I could call a method inside this e.g. startLoading: and in an ideal world this method would just return an array but it cannot, as the notifications should be loaded asynchronous. I also have to take into account that the asynchrnonous request might return an error in connection:didFailWithError:
Can anyone give me a hint or an example of how I can make a class which does an asynchronous load and returns the result? I imagine this class should be called like this:
NotificationLoader *notificationLoader = [NotificationLoader alloc] init];
NSArray *notifications = [notificationLoader startLoading];
Though, I’m not sure that’s the best way to do it.
If you want it to be asynchronously you should use the delegation pattern. Define a protocol which needs to be implemented by the class which calls the NotificationLoader, When calling startLoading the method should start a separate thread (or using NSURL for starting an asychronous call) and loading all the stuff asynchronously. When it’s done it will call either the ‘finishedLoadingResults:(NSArray*)results’ method on the delegate (which is declared in the protocol) or the ‘didFailWithError’
so you just call
Example for your NotificationLoader:
Implementation of the NotificationLoader