NSCache auto-removal policy

前端 未结 2 739
野性不改
野性不改 2021-02-08 23:36

What are some of the NSCache\'s auto-removal policies? Apple\'s documentation does not mention them, and I experimentally discovered that NSCache does not respond to memory war

2条回答
  •  再見小時候
    2021-02-09 00:18

    NSCache does not respond to UIApplicationDidReceiveMemoryWarningNotification, but it does automatically evict its objects in low memory situations, obviously using some other mechanism.

    While I previously suggested observing UIApplicationDidReceiveMemoryWarningNotification, this is not the case. No special handling for low memory situations is needed, as NSCache handles this automatically.


    Update:

    As of iOS 7, the NSCache not only doesn't respond to memory warnings, but it also does not appear to properly purge itself upon memory pressure, either (see NSCache crashing when memory limit is reached (only on iOS 7)).

    I subclass NSCache to observe UIApplicationDidReceiveMemoryWarningNotification, and purge the cache upon memory warning:

    @interface AutoPurgeCache : NSCache
    @end
    
    @implementation AutoPurgeCache
    
    - (id)init
    {
        self = [super init];
        if (self) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
        }
        return self;
    }
    
    - (void)dealloc
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
    
        // if not ARC, also
        //
        // [super dealloc];
    }
    
    @end
    

提交回复
热议问题