我在Objective-C iOS的AFURLSessionManager中遇到问题。我有2个viewController,并使用AFURLSessionManager从服务器获取数据。

当用户导航到具有AFURLSessionManager请求的viewContoller2且用户的网络非常差并按“后退”按钮时,AFURLSessionManager想要调用委托,崩溃并显示 EXC_BAD_ACCESS(code = EXC_I386_GPFLT)

ios - 当我的ViewController导航的应用崩溃时,AFURLSessionManager崩溃了-LMLPHP

当我导航到viewController时,AFURLSessionManager任务延迟完成,并且用户和AFURLSessionManager更改了viewController,而MEMORY中不存在调用委托。

任何人有解决这个问题的主意吗?

这是请求代码:

- (void) getData
{
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"GET" URLString:@"http://----------" parameters:nil error:nil];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    req.timeoutInterval= 15;
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    self.dataTask = [manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error)
     {

         if (!error)
         {
             NSLog(@"Reply JSON >>>>>> responseObject <<<<<: %@", responseObject);


             if ([responseObject isKindOfClass:[NSDictionary class]])
             {
                 if (self.delegate && [self.delegate respondsToSelector:@selector(success:)]) {
                     [self.delegate success:responseObject];
                 }
                 //                  self.colorView.backgroundColor = [UIColor blueColor];
                 return;
             }
             else
             {
                 NSLog(@"Error No dictionary: %@, %@, %@", error, response, responseObject);
                 {
                     //                      self.colorView.backgroundColor = [UIColor redColor];
                     [self.delegate error:error];
                     return;
                 }

             }
         }
         else
         {
             NSLog(@"Error: %@, %@, %@", error, response, responseObject);
             [self.delegate error:error];
             return;

         }

     }];

    [self.dataTask resume];

    if (self.cancelRequest) {
        [self.dataTask cancel];
    }
}

头文件:
@protocol WebServicesDelegate <NSObject>

- (void) success:(NSDictionary *) dic;
- (void) error:(NSError *) error;

@end

@interface WebServices : NSObject

@property (assign,nonatomic) id<WebServicesDelegate> delegate;
@property (nonatomic) BOOL cancelRequest;

-(void) setCancelRequest:(BOOL)cancelRequest;
//+(instancetype) shareInstance;

- (void) getData;

@end

提前致谢

最佳答案

调试什么是self.delegate。绝对不是零,否则它不会崩溃。

由于self.delegate不是NSObject子类,因此崩溃了。它可以是标量或某些垃圾值。

我猜您在声明委托时使用了assign而不是weak,并且由于分配了委托,因此导致指针悬空。

编辑(问题更新后)
更改

@property (assign,nonatomic) id<WebServicesDelegate> delegate;


@property (weak,nonatomic) id<WebServicesDelegate> delegate;

09-12 18:56