找到你要的答案

Q:Network request comes back after the controller is popped

Q:网络请求回来后,控制器弹出

I make a network request within a viewcontroller, the simplified code is as below:

- (void)viewDidLoad {

    [super viewDidLoad];

    [self http_request];

}

- (void)http_request {

    dispatch_async(gAsynQueueT, ^{

        NSString *response;

        NSURL *url = [NSURL URLWithString:@"http://www.google.com"];

        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

        sleep(5); //leave some time for poping this controller

        [request startSynchronous];

        NSError *error = [request error];

        if (!error) {

           response = [request responseString];

        }

        dispatch_async(gMainQueueT, ^{

            _data = response;  //_data is an global variable

        });

    });


}

Before the network request coming back, I popped the controller. I think this should lead to memory leak, cause when the network request came back the controller is released. But I found nothing wrong with instrument tool.

So, how to expain this situation. Thanks~

我做了一个网络请求在一个视图控制器,简化代码如下:

- (void)viewDidLoad {

    [super viewDidLoad];

    [self http_request];

}

- (void)http_request {

    dispatch_async(gAsynQueueT, ^{

        NSString *response;

        NSURL *url = [NSURL URLWithString:@"http://www.google.com"];

        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

        sleep(5); //leave some time for poping this controller

        [request startSynchronous];

        NSError *error = [request error];

        if (!error) {

           response = [request responseString];

        }

        dispatch_async(gMainQueueT, ^{

            _data = response;  //_data is an global variable

        });

    });


}

在网络请求回来之前,我弹出了控制器。我认为这会导致内存泄漏,因为当网络请求回来时控制器被释放。但我发现仪器工具没有错。

那么,如何解释这种情况。谢谢~

answer1: 回答1:

You already used dispatch_async(gAsynQueueT, {...}) and it will run on another thread.

And in block, you didn't use view controller's property so I think there is no reason for memory leak.

block was already dispatched to queue so it isn't related to view controller anyway.

你已经用dispatch_async(gasynqueuet,{…}),它将运行在另一个线程。

在块中,你没有使用视图控制器的属性,所以我认为没有内存泄漏的原因。

块已被发送到队列,所以它与视图控制器无关。

ios  objective-c  networking  httprequest