NSCache VS NSPurgableData

Discussion in 'iOS Programming' started by daproject85, Nov 6, 2012.

  1. daproject85 macrumors member

    Apr 13, 2011
    Hi Forum,

    I have read the apple docs for both NScache and NSPurgableData and still dont know the pros and cons. Any help is appreciated..

    and also the totalcostlimit and countlimit methods of the NSCache class...... thetotalcost sets the size in megabytes? kilobytes? gigabytes?

    the countlimit clearly handles the # of items, but what about if i want a cache with a 10MB limit
  2. Reason077 macrumors 68010


    Aug 14, 2007
    If you wanted an NSCache with a 10MB limit, you'd:

    - set totalCostLimit to (1024 * 1024).
    - Use setObject:forKey:cost: when adding objects to the cache, specifying the size of each object you're adding (in bytes).

    The NSCache should then start automatically evicting objects once the size exceeds 10MB.
  3. daproject85 thread starter macrumors member

    Apr 13, 2011
    Reasons: so the unit for totalcostlimit is in bytes then?
  4. chown33 macrumors 604

    Aug 9, 2009
    The cost units are arbitrary. The units are whatever you want them to be. You add items with a cost given for each one. As long as they're all using the same units, everything will work.

    Suppose you want a limit 100 MB, with units of 1 MB. Then the limit would be the integer 100, and each item added has an associated integer cost measured in MB: 1, 2, 3, etc..

    If you want the same limit of 100 MB, with units of 100 KB, then multiply everything by 10. So the limit would be 1000, and every item's integer cost would be measured in tenths of a MB.
  5. Reason077 macrumors 68010


    Aug 14, 2007
    As chown33 says, the 'cost' can be whatever unit you want. eg: Kilowatts, Yuan Renminbi, or even magic beans. But I would strongly recommend using bytes in most instances.

    Using megabytes as your unit, as chown33 suggests, might not be a good idea as it would be subject to fairly wide variance due to rounding. What would happen if you added 1 million objects of 1kb each, for example?
  6. chown33 macrumors 604

    Aug 9, 2009
    I wasn't suggesting megabytes as units, merely using it as an illustrative example.

    The main thing that would be a problem is giving an item a cost of zero.

    There should never be a zero-cost object. The mathematical reasons for this should be obvious. You can add 0 to any number, any number of times, and the resulting sum will be unchanged. So 900 + 0 = 900 + 0 + 0 + 0 + 0 + 0 + 0 + 0. Clearly, giving items a cost of 0 causes them to "disappear" from all calculations involving the limit.

    Maybe there's failsafe code in NSCache that imposes a lower limit on cost, so passing 0 is actually evaluated as a cost of 1 (the minimum usable cost). Or maybe it throws an exception if a cost is 0. Personally, I wouldn't bet on anything; simply avoid zero or add your own failsafe.

Share This Page