iOS开发架构封装异步请求案例实现
iOS开发架构封装异步请求案例实现是本文要介绍的内容,主要是实现iOS开发中异步请求的封装案例,来看本文详细内容讲解。
在找iOS开发相关的内容是,看到本文,与朋友们分享一下。论坛里看到一位兄台的问题:”异步请求能不能封装成一个公用的类?每个页面都要copy一下几个方法,感觉很麻烦“可能很多人也会有相同的问题,于是起一篇博客专门谈谈这个问题,主要想阐述一下编程思想及架构设计,权当抛砖引玉。闲话不多说,直接上代码:
//MyURLClass.h
#import <Foundation/Foundation.h>
@interface MyURLClass : NSObject {
@private
NSMutableSet *mDelegates;
NSMutableData *mData;
}
- (void) addDelegate:(id)delegate;
- (void) removeDelegate:(id)delegate;
@end
//MyURLClass.m
@implementation MyURLClass
- (id)init {
[super init];
mDelegates = [NSMutableSet new];
mData = [NSMutableData new];
return self;
}
- (void) addDelegate:(id)delegate {
[mDelegates addObject:delegate];
}
- (void) removeDelegate:(id)delegate{
[mDelegates removeObject:delegate];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[mData appendData:data];
}
- (void) connectionDidFinishLoading : (NSURLConnection *) connection {
NSLog(@"delegate:%@", mDelegates);
SEL seltor = @selector(finishWithData:);
NSSet * set = [[NSSet alloc] initWithSet:mDelegates];
for (id del in set) {
if ([del respondsToSelector:seltor])
[del performSelector:seltor withObject:mData];
}
[set release];
}
@end
至此,我的“异步请求类”就封装好了,mDelegates是用来保存请求对象(即发送异步请求的那个类的对象)的,以便在异步connectionDidFinishLoading的时候调用回调方法,继续:
- (IBAction)sendMyRequest {
NSURL *url = [NSURL URLWithString:@"http://www.csdn.net"];
NSURLRequest *mRequest = [NSURLRequest requestWithURL:url];
MyURLClass *urlClass = [[MyURLClass alloc] init];
[urlClass addDelegate:self];
[[NSURLConnection alloc] initWithRequest:mRequest delegate:urlClass startImmediately:YES];
}
- (void)finishWithData:(NSData *)data {
NSLog(@"%@", data);
}
- (IBAction)sendMyRequest {
&n
相关新闻>>
- 发表评论
-
- 最新评论 更多>>