NSURLSession Memory Leaks occur when using web services in IOS

前端 未结 4 958
面向向阳花
面向向阳花 2021-01-31 18:54

I am building an app that uses a web service and to get information from that web service I use NSURLSession and NSURLSessionDataTask.

I am now

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-31 19:25

    Had the same issue. The @Jonathan's answer didn't make a sense - my app still leaked memory. I found out that setting the session property to nil in URLSession:didBecomeInvalidWithError: delegate method is causing the issue. Tried to look deeper into the URL Loading System Programming Guide. It says

    After invalidating the session, when all outstanding tasks have been canceled or have finished, the session sends the delegate a URLSession:didBecomeInvalidWithError: message. When that delegate method returns, the session disposes of its strong reference to the delegate.

    I left the delegate method blank. But the invalidated session property still have a pointer, when should I set it nil? I just set this property weak

    // .h-file
    @interface MyClass : NSObject 
    {
      __weak NSURLSession *_session;
    } 
    
    // .m-file
    - (NSURLSessionTask *)taskForRequest:(NSURLRequest *)request  withCompletionHandler:(void(^)(NSData *,NSURLResponse *,NSError *))handler
    {
      if(!_session)
        [self initSession];
      //...
    }
    

    The app stopped leaking memory.

提交回复
热议问题