Obj-C类发出异步请求

时间:2011-08-26 08:05:25

标签: iphone objective-c class asynchronous request

我正在开发一个iPhone应用程序,我需要使用Facebook的FQL来加载用户的通知。由于我需要在应用程序中加载这些通知的不同位置,我想使NSObject的子类加载并将这些通知作为数组返回。 我知道我应该创建一个子类(NotificationLoader),然后我可以调用一个方法,例如startLoading:并且在一个理想的世界中,这个方法只会返回一个数组,但它不能,因为通知应该是异步加载的。我还必须考虑到异步请求可能会在connection:didFailWithError:

中返回错误

任何人都可以给我一个提示或一个例子,说明如何创建一个执行异步加载并返回结果的类?我想这个类应该像这样调用:

NotificationLoader *notificationLoader = [NotificationLoader alloc] init];
NSArray *notifications = [notificationLoader startLoading];

虽然,我不确定这是最好的方法。

4 个答案:

答案 0 :(得分:2)

如果您希望它是异步的,您应该使用delegation pattern。定义一个需要由调用NotificationLoader的类实现的协议。当调用startLoading时,该方法应该启动一个单独的线程(或者使用NSURL来启动异步调用)并异步加载所有的东西。完成后,它将调用委托上的'finishedLoadingResults:(NSArray *)结果'(在协议中声明)或'didFailWithError'

所以你只需要打电话

 -(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...
 }

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

NotificationLoader的实施

 @implementation NotificationLoader
 @synthesize delegate;

 -(void) startLoading{
       NSArray * myResults = ....;
       // Call delegate:
       [delegate notificationLoader:self didFinishWithResults:  myResults];
 }

答案 1 :(得分:1)

您只需要创建一个url连接并将委托传递给它。它将是异步的。

NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];    

答案 2 :(得分:1)

如果您需要发出HTTP请求,我强烈建议您使用ASIHTTPRequest

答案 3 :(得分:1)

我更喜欢使用ASIHTTPRequest来处理同步和异步请求。