[英]Obj-C class to make asynchronous request
我正在開發一個iPhone應用程序,需要在其中使用Facebook的FQL加載用戶的通知。 由於需要在應用程序中的不同位置加載這些通知,因此我想制作一個NSObject的子類來加載並以數組形式返回這些通知。 我知道我應該創建一個子類( NotificationLoader
),然后可以在其中調用一個方法,例如startLoading:
在理想情況下,該方法將僅返回一個數組,但不能返回數組,因為通知應異步加載。 我還必須考慮到異步請求可能會在connection:didFailWithError:
返回錯誤connection:didFailWithError:
誰能給我一個提示或示例,說明如何制作一個異步加載並返回結果的類? 我想象這個類應該這樣調用:
NotificationLoader *notificationLoader = [NotificationLoader alloc] init];
NSArray *notifications = [notificationLoader startLoading];
不過,我不確定這是最好的方法。
如果希望它是異步的,則應使用委托模式 。 定義一個需要由調用NotificationLoader的類實現的協議,在調用startLoading時,該方法應啟動一個單獨的線程(或使用NSURL進行異步調用)並異步加載所有內容。 完成后,它將在委托上調用“ finishedLoadingResults:(NSArray *)results”方法(在協議中聲明)或“ 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];
}
您只需要創建一個url連接並將一個委托傳遞給它即可。 它將是異步的。
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
如果您需要發出HTTP請求,我強烈建議您使用ASIHTTPRequest 。
我更喜歡使用ASIHTTPRequest來處理同步和異步請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.