項(xiàng)目初期,項(xiàng)目經(jīng)理提出一個(gè)需求,如下:
每一個(gè)controller要單獨(dú)管理自己的網(wǎng)絡(luò)請求操作捂掰,在controller銷毀的時(shí)候要取消掉相應(yīng)的網(wǎng)絡(luò)請求。
為了整個(gè)項(xiàng)目統(tǒng)一曾沈,我們需要在基類中來實(shí)現(xiàn)这嚣,為了區(qū)別我們新建一個(gè)基類的category。
當(dāng)然我們需要用一個(gè)數(shù)組來存放我們的操作塞俱,可是category又不能直接添加成員變量姐帚,那我們可以直接通過runtime來直接關(guān)聯(lián)一個(gè)變量:
頭文件如下:
#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
具體實(shí)現(xiàn)如下:
#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
這樣每一個(gè)controller都可以單獨(dú)的管理自己的網(wǎng)絡(luò)請求操作了