Sobes.tech
Middle+

How would you implement memory cleanup through stored types and keys?

sobes.tech AI

Answer from AI

Would use NSCache or specialized cache managers. NSCache automatically manages memory by evicting objects when needed.

Example with NSCache:

import Foundation

class DataCache {
    private let cache = NSCache<NSString, NSData>() // Cache for data

    func setData(_ data: Data, forKey key: String) {
        let nsKey = key as NSString
        let nsData = data as NSData
        cache.setObject(nsData, forKey: nsKey) // Save data for key
    }

    func getData(forKey key: String) -> Data? {
        let nsKey = key as NSString
        guard let nsData = cache.object(forKey: nsKey) else {
            return nil
        }
        return nsData as Data // Retrieve data for key
    }

    func removeData(forKey key: String) {
        let nsKey = key as NSString
        cache.removeObject(forKey: nsKey) // Remove data for key
    }

    func removeAllData() {
        cache.removeAllObjects() // Clear entire cache
    }
}

NSCache has advantages over NSDictionary or Swift.Dictionary for caching:

  • Automatic eviction: Removes objects when memory is low.
  • Thread safety: Safe to use from multiple threads.
  • Weak references: Does not hold strong references to objects, preventing memory leaks.

For more complex caching logic (e.g., expiration or size limits), you can create your own cache manager class that wraps NSCache or uses other mechanisms (like disk storage with file system management).

How would you implement memory cleanup through stored… - sobes.tech