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 loa开发者_StackOverflowded 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
-(void) someMethod{
NotificationLoader *notificationLoader = [NotificationLoader alloc] init];
notificationLoader.delegate = self;
[notificationLoader startLoading];
}
-(void) notificationLoaderDidLoadResults:(NSArray*) results
{
// This is the place where you get your results.
}
-(void) notificationLoaderDidFailWithError:....
{
// or there was an error...
}
Example for your NotificationLoader:
@protocol NotificationLoaderDelegate;
@interface NotificationLoader : NSObject
@property(nonatomic,retain) id<NotificationLoader> delegate;
-(void) startLoading;
@end
// Define the methods for your delegate:
@protocol NotificationLoaderDelegate <NSObject>
-(void) notificationLoader:(NotificationLoader*) notifloader didFinishWithResults:(NSArray*) results;
-(void) notificationLoader:(NotificationLoader*) notifloader didFailWithError;
@end
Implementation of the NotificationLoader
@implementation NotificationLoader
@synthesize delegate;
-(void) startLoading{
NSArray * myResults = ....;
// Call delegate:
[delegate notificationLoader:self didFinishWithResults: myResults];
}
You just need to create a url connection and pass a delegate to it. It will be asynchronous.
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
If you need to make an HTTP request, I would highly recommend using ASIHTTPRequest.
I prefer to use ASIHTTPRequest to handle both synchronous and asynchronous requests.
精彩评论