Iphone 用于发出异步请求的Obj-C类
我正在开发一个iPhone应用程序,其中我需要使用Facebook的FQL来加载用户的通知。由于我需要在应用程序中的不同位置加载这些通知,我想创建一个NSObject的子类来加载这些通知并将其作为数组返回。 我知道我应该创建一个子类(Iphone 用于发出异步请求的Obj-C类,iphone,objective-c,class,asynchronous,request,Iphone,Objective C,Class,Asynchronous,Request,我正在开发一个iPhone应用程序,其中我需要使用Facebook的FQL来加载用户的通知。由于我需要在应用程序中的不同位置加载这些通知,我想创建一个NSObject的子类来加载这些通知并将其作为数组返回。 我知道我应该创建一个子类(NotificationLoader),然后我可以在其中调用一个方法,例如starting:,在理想情况下,这个方法只返回一个数组,但它不能,因为通知应该异步加载。我还必须考虑到异步请求可能会在连接中返回错误:didFailWithError: 有人能给我一个提示或
NotificationLoader
),然后我可以在其中调用一个方法,例如starting:
,在理想情况下,这个方法只返回一个数组,但它不能,因为通知应该异步加载。我还必须考虑到异步请求可能会在连接中返回错误:didFailWithError:
有人能给我一个提示或示例,说明我如何创建一个进行异步加载并返回结果的类吗?我想这门课应该这样称呼:
NotificationLoader *notificationLoader = [NotificationLoader alloc] init];
NSArray *notifications = [notificationLoader startLoading];
不过,我不确定这是最好的方法。您只需要创建一个url连接并向其传递一个委托。它将是异步的
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
如果您需要发出HTTP请求,我强烈建议使用。如果您希望它是异步的,您应该使用。定义一个需要由调用NotificationLoader的类实现的协议,当调用StartLoad时,该方法应该启动一个单独的线程(或者使用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
我更喜欢使用ASIHTTPRequest来处理同步和异步请求。如果我这样做,那么我的
通知数组(在NotificationLoader
类之外创建)不会有值,因为startLoading
不会返回数组,因为它只会启动请求,并将在connection:didLoad:
中结束。我可能会让它变得更难,但我真的不知道该怎么做。AsittpRequest确实很棒。在这种情况下,我将使用facebook ios sdk,因此我将提出FBI请求。我从未尝试过创建自己的代理,但这似乎是一个很好的解决方案。我正在阅读有关代表的资料,并以这种方式进行。
@implementation NotificationLoader
@synthesize delegate;
-(void) startLoading{
NSArray * myResults = ....;
// Call delegate:
[delegate notificationLoader:self didFinishWithResults: myResults];
}