当我构建我的应用程序时,我创建了一个名为NetEngine的类来管理所有网络请求。但我发现在我退出使用NetEngine的视图控制器之后,我仍然会调用成功或失败块。
的ViewController:
[[NetEngine engine] GET:httpUrl success:^(id responseObject) {
//some code here
//It's still called after I quit viewctroller
} failure:^(NSError *error) {
//some code here
//It's still called after I quit viewctroller
}];
NetEngine:
typedef void(^SuccessBlock) (id responseObject);
typedef void(^FailureBlock) (NSError *error);
@interface NetEngine ()
@property (nonatomic, strong) AFHTTPSessionManager *httpManager;
@end
@implementation NetEngine
+ (NetEngine *)engine {
static NetEngine *_sharedEngengine = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedEngengine = [[self alloc] init];
});
return _sharedEngengine;
}
- (id)init {
if (self = [super init]) {
_httpManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:BZTVBaseServerPath]];
[_httpManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"accept"];
_httpManager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
_httpManager.operationQueue.maxConcurrentOperationCount = 4;
[_httpManager.requestSerializer setTimeoutInterval:10.0];
}
return self;
}
- (void)GET:(NSString *)URLString success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock {
// some thing about cache
[_httpManager GET:encodeUrl parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
[[self defaultCache] setObject:responseObject forKey:cacheKey];
if (successBlock) {
successBlock(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (isCache) {
if (successBlock) {
successBlock([[self defaultCache] objectForKey:cacheKey]);
}
}
if (failureBlock) {
failureBlock(error);
}
}];
}
答案 0 :(得分:1)
来自文档:"块是添加到C,Objective-C和C ++的语言级功能,它允许您创建可以传递给方法或函数的不同代码段,就像它们一样值&#34 ;.因此,块本身就是一个对象,这意味着它的生命周期不依赖于创建它的对象。
如果您不希望NetEngine
使用您提供给它的代码,那么当您退出时,您需要一种方法将该信息传递给它。视图控制器。
基本上:
[[NetEngine engine] GET:httpUrl success:^(id responseObject) {
// if the view controller still wants me to do this {
//some code here
// }
} failure:^(NSError *error) {
// if the view controller still wants me to do this {
//some code here
// }
}];
答案 1 :(得分:0)
如果要在退出视图控制器时取消网络呼叫,请执行以下操作:
创建cancel
BOOL
变量
添加viewWillDisappear
方法:
-(void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
cancel = YES;
}
检查回调方法中取消是否为
[[NetEngine engine] GET:httpUrl success:^(id responseObject) {
//some code here
//It's still called after I quit viewctroller
if (!cancel) {
//do what you have to do
}
} failure:^(NSError *error) {
//some code here
//It's still called after I quit viewctroller
if (!cancel) {
//do what you have to do
}
}];