Junior — Middle
Could you explain the principle of data caching system operation?
sobes.tech AI
Answer from AI
The data caching system is designed for temporary storage of frequently used information to speed up access and reduce load on primary data sources (such as networks or databases).
The caching principle is as follows:
- When data is requested, it first checks if the information is in the cache.
- If the data is found (cache hit), it is returned immediately, which is much faster.
- If the data is not found (cache miss), it is loaded from the main source, and then stored in the cache for future requests.
In iOS, NSCache is often used for caching, which automatically manages memory and removes objects when necessary. Data can also be cached on disk to persist between app launches.
Example of using NSCache:
let imageCache = NSCache<NSString, UIImage>()
func loadImage(urlString: String) -> UIImage? {
if let cachedImage = imageCache.object(forKey: urlString as NSString) {
return cachedImage
}
// Load image from network or another source
// After loading:
// imageCache.setObject(loadedImage, forKey: urlString as NSString)
return nil
}