gpt4 book ai didi

ios - 退出 View Controller 后不要调用回调 block

转载 作者:行者123 更新时间:2023-11-29 00:52:18 28 4
gpt4 key购买 nike

当我构建我的应用程序时,我创建了一个名为 NetEngine 的类来管理所有网络请求。但是我发现在退出使用 NetEngine 的 View Controller 后,我仍然调用成功或失败 block 。

View Controller :

    [[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
}];

网络引擎:

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);
}
}];
}

最佳答案

来自文档:“ block 是添加到 C、Objective-C 和 C++ 的语言级功能,它允许您创建不同的代码段,这些代码段可以像值一样传递给方法或函数”。因此, block 本身是一个对象,这意味着它的生命周期不依赖于创建它的对象。

如果您不希望 NetEngine 使用您提供给它的代码,您需要一种在您“退出” View Controller 时将信息传递给它的方法。

基本上:

[[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
// }
}];

关于ios - 退出 View Controller 后不要调用回调 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37992562/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com