项目初期,项目经理提出一个需求,如下:
每一个controller要单独管理自己的网络请求操作,在controller销毁的时候要取消掉相应的网络请求。
为了整个项目统一,我们需要在基类中来实现,为了区别我们新建一个基类的category。
当然我们需要用一个数组来存放我们的操作,可是category又不能直接添加成员变量,那我们可以直接通过runtime来直接关联一个变量:
头文件如下:
#import <UIKit/UIKit.h>
@class AFHTTPRequestOperation;
@interface UIViewController (Operation)
@property(nonatomic,readonly)NSMutableArray *operations;
-(void)addOperation:(AFHTTPRequestOperation *)operation;
-(void)removeOperation:(AFHTTPRequestOperation *)operation;
-(void)cancelAllOperation;
@end
具体实现如下:
#import "UIViewController+Operation.h"
#import <objc/runtime.h>
#import "XYQApi.h"
@implementation UIViewController (Operation)
static char kOperationKey;
- (void)setOperations:(NSMutableArray *)operations{
if (!operations) {
operations = [[NSMutableArray alloc]init];
objc_setAssociatedObject(self, &kOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
}
-(NSMutableArray *)operations
{
return objc_getAssociatedObject(self, &kOperationKey);
}
-(void)addOperation:(AFHTTPRequestOperation *)operation
{
[self.operations addObject:operation];
}
-(void)removeOperation:(AFHTTPRequestOperation *)operation
{
[self.operations removeObject:operation];
}
-(void)cancelAllOperation
{
for (AFHTTPRequestOperation * op in self.operations) {
[XYQApi cancelOperation:op];
}
[self.operations removeAllObjects];
}
@end
这样每一个controller都可以单独的管理自己的网络请求操作了