0

In iOS and using Objective C and Grand Central Dispatch (GCD) I want to fetch data on a background thread then return with data to the main thread, but am having trouble with memory leaks. Could someone please help me change the below code to not have memory leaks. I think I need to use "weak self" somehow?

- (void) startLoadData { // called from main thread
   dispatch_queue_t qBGThread = dispatch_queue_create("MyApp.loadDataBGThread", NULL);
   dispatch_async(qBGThread, ^ { [self loadSomeDataOnBGThread]; });
}
- (void) loadSomeDataOnBGThread {
    MyResponse *response = [DataFetcher getSomeData];
    dispatch_async(dispatch_get_main_queue(), ^{[self loadDataFinished: response];});
}
- (void) loadDataFinished:(MyResponse *)response {
    // back on main thread
    if (response.successful) {
        [self displayData: response]
    } else {
        // handle data fetch error
    }
}
NedMed
  • 1
  • 1
  • There is nothing in the code shown that will cause a memory leak. What leak is the Leaks instrument showing? – Paulw11 Apr 05 '22 at 20:25
  • How did you determine you have a leak? If it's a real “leak”, you‘d use Instruments’ Leaks tool (via Xcode’s “Product” » “Profile” command). If it was a strong reference cycle or the like, you’d use Xcode’s “Debug Memory Graph” to find the problem (as illustrated [here](https://stackoverflow.com/a/30993476/1271826)). If it is just a little bump in memory, if could just be the caching of data in the `NSURLCache`. Bottom line, show us precisely how you concluded there was a leak as there are a variety of different sources of memory consumption. – Rob Apr 05 '22 at 23:59
  • Thanks for your replies @Pawlw11 and Rob. I think there is a leak because after a few days the app and the whole phone slows down dramatically until the app is shutdown. On the debug navigator the memory always climes higher as the app is used. – NedMed Apr 06 '22 at 00:11
  • I would recommend “debug memory graph” as discussed in that other post and the videos I linked to there to diagnose it. But the code listed in the question is unlikely to be the source of the problem. – Rob Apr 06 '22 at 00:33

0 Answers0