Simple use of Nscache

Source: Internet
Author: User
Tags at sign



Brief introduction



1) Nscache is Apple's official cache class, and usage is similar to Nsmutabledictionary's usage, which is used in afnetworking and sdwebimage to manage caching.



2) Nscache automatically releases some objects when the system memory is low (note: The cache does not clean up when memory warnings are in the emulator). In development to ensure that memory is actually freed when a memory warning is received, it is best to call-(void) removeallobjects; Method.



3) Nscache is thread-safe, in multi-threaded operation, do not need to nscache lock.



4) Nscache key is only a strong reference, do not need to implement the Nscopying protocol



Property:

/ * * name * /
@ property (copy) nsstrings * name;
Agent / * * * /
Property (nullable, assign) id<nscachedelegate> delegate;</nscachedelegate>
/** the maximum total cost of the cache space, beyond which the object will be automatically reclaimed. The default value is 0, indicating that there is no limit */
@ property NSUInteger totalCostLimit;
The maximum number of objects that can be cached. The default value is 0, indicating that there is no limit */
@ property NSUInteger countLimit;
/** identifies whether the cache recycles obsolete content. The default value is YES, indicating automatic recycling of */
@ property BOOL evictsObjectsWithDiscardedContent;
Methods:

/ * *
Returns the object associated with the key
* /
- (nullable ObjectType) objectForKey (KeyType) key;

/ * *
Set the value of the specified key name in the cache. Unlike the variable dictionary, the cache object does not copy the key name
* /
- (void) setObject (ObjectType) obj forKey: KeyType) key;

/ * *
Sets the value corresponding to the specified key name in the cache and specifies the cost of the key-value pair. When a memory warning occurs, or when the total cost of the cache is exceeded, the cache starts a recovery process that removes some elements
Param cost (cost) is used to calculate the total cost of all objects recorded in the buffer
* /
- (void) setObject (ObjectType) obj forKey: (KeyType) key cost (NSUInteger) g;

/ * *
Deletes the object in the cache that specifies the key name
* /
- (void) removeObjectForKey (KeyType) key;

/ * *
Delete all objects in the cache
* /
- (void) removeAllObjects;
Delegation method:

/ * *
Called when the cache is about to delete an object. Note: you cannot modify the cache in this method!!
* /
- (void) cache: (NSCache *) cache willEvictObject obj (id);


Simple example:

/ * *

* here is an example of how to use caching

* requirements: the string is cached, viewed, and cleaned up.

* ready: add buttons in main. storyboard for add, check, and remove caches, respectively. (test here in a cost effective way)

* /
1. Create a cache object

/** cache attribute */
Property (nonatomic, strong) NSCache *cache;
// create cache objects by lazy loading
Cache - (NSCache *) {
If (! _cache) {
_cache = [[NSCache alloc] init];
// set cost to 5 NSCache automatically retrieves the object when more data is stored than the total value
_cache. TotalCostLimit = 5;
// setting up the proxy method is usually not used, but is usually used when testing
_cache. Delegate = self;
}
Return _cache;
}
2. Click method to realize the button

// add cache
- (IBAction) addCache {
For (int I = 0; I < 10; I++) {
NSString * STR = [NSString stringWithFormat:@" stored here "];
// set the cost to 1
[the self. The cache setObject: STR forKey: @ (I) cost: 1);
NSLog(@" store data --%@",@(I));
}
}
// check the cache
- (IBAction) checkCache {
NSLog (@ "-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
For (int I = 0; I < 10; I++) {
NSString * STR = [self.cache objectForKey:@(I)];
If (STR) {
NSLog(@" retrieve data stored in cache --%@",@(I));
}
}
}
// clear the cache
- (IBAction) deleteCache {
[the self. The cache removeAllObjects];
NSLog(at sign "clear the cache ");
}
3. Implement the proxy

# pragma mark - NSCacheDelegate
// calls when objects are about to be reclaimed, following the NSCacheDelegate protocol before implementing proxy methods.
- (void) cache: (NSCache *) cache willEvictObject obj (id) {
NSLog (@ "recycling -- -- -- -- -- -- -- -- % @", obj);
}
4. Print instructions

4.1 click the add button to print

Store data --0

Store data --1

Store data --2

Store data --3

Store data --4

Recycling - storing data here

Store data --5

Recycling - storing data here

Store data --6

Recycling - storing data here

Store data --7

Recycling - storing data here

Store data --8

Recycling - storing data here

Store data --9

4.2 click the check button to print

---------------------------------------------

Retrieve the data stored in the cache

Retrieve the data stored in the cache

Retrieve the data stored in the cache

Retrieve the data stored in the cache

Get the data out of the cache

4.3 interpretation of printing

Here, since each string object is stored at a cost of 1, we set the total cost at 5, the string object is stored 10 times, the total cost is 10, so the string object of data 1 is retrieved when data 5 is stored, and so on, so the printed result is shown above. The cleanup of the cache and other related operations are left to the reader to print, and I won't go into detail here.
Supplement:

/ * *

* if the cache was added to the example as follows, there would be no recycled print, and there would be 10 pieces of data when the cache was checked.

* explanation: NSCache's Key is a Strong reference to the object, not a copy.

* when written outside of the for loop, so for string objects only 10 strong references are created in memory, while only one real string object is stored (the string object is created only once), so the total cost is 1.

* when written inside the for loop, the string object simply creates 10 strong references in memory, whereas the actual string object is stored in ten (creating new string objects each time), so the total cost is 10.

* /

// add cache
- (IBAction) addCache {
// NSCache's Key is a Strong reference to the object, not a copy,
NSString * STR = [NSString stringWithFormat:@" stored here "];
For (int I = 0; I < 10; I++) {
// set the cost to 1
[the self. The cache setObject: STR forKey: @ (I) cost: 1);
NSLog(@" store data --%@",@(I));
}
Simple use of NSCache

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.