iOS Memory issue (ARC) when downloading and saving large ammount of images from server

后端 未结 2 726
猫巷女王i
猫巷女王i 2021-02-04 21:04

The following code downloads 700+ images from a server with varying sizes, the issue here is that memory (even with ARC) is never released and eventually a memory warning appear

2条回答
  •  Happy的楠姐
    2021-02-04 21:39

    Based on your screenshot, I think the issue is with the NSURL caching rather than the actual NSData objects. Can you try the following:

    In your Application Delegate, setup an initial URL cache:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        // Do initial setup
        int cacheSizeMemory = 16*1024*1024; // 16MB
        int cacheSizeDisk = 32*1024*1024; // 32MB
        NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
        [NSURLCache setSharedURLCache:sharedCache];
    
        // Finish the rest of your didFinishLaunchingWithOptions and head into the app proper
    }
    

    Add the following to your Application Delegate:

    - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
        [[NSURLCache sharedURLCache] removeAllCachedResponses];
    }
    

    A cache file will be created:"Library/Caches/your_app_id/nsurlcache"

    The link to the Apple example is here: URL Cache

    Code not tested but this (or something similar) should sort your problem + plus you can experiment with the cache sizes.

    Can you post another screenshot of Allocations in action with this code? I would expect to see memory use stop growing and flatten out.

提交回复
热议问题