OBJECTIVE-C Cache Framework Egocache use in IOS app development _ios

Source: Internet
Author: User
Tags current time

Egocache Introduction

Egocache is a simple, Thread-safe key value cache store. It has native support for NSString, Ui/nsimage, and NSData, but can store anything that implements <NSCODING>. All cached items expire on the timeout, which by default, are one day.
Translation is: Egocache a simple, thread-safe key-value caching framework, native support NSString, Ui/nsimage, and NSData, also supports the storage of any implementation of the Protocol class, you can set cache expiration time, default is 1 days.

Egocache has only one class, EGOCache.h and egocache.m two files. Usage is also easier to master, carefully study the EGOCache.h method, can soon get started.

Egocache only provides disk caching and does not provide a memory cache. It also provides a way to clean the cache:

Copy Code code as follows:

-(void) ClearCache;

Egocache also provides a way to determine whether a cache exists:
Copy Code code as follows:

-(BOOL) Hascacheforkey: (nsstring* __nonnull) key;

join projects directly through Cocoapods

Add the following line directly to the Podfile of your project:

Copy Code code as follows:

Pod ' Egocache '

Then execute:
Copy Code code as follows:

$ pod Update

Egocache usage

Cache NSString with Egocache

Store:

Copy Code code as follows:

NSString *savestring = @ "Save Me";
[[Egocache Globalcache] setstring:savestring forkey:[nsstring stringwithformat:@ ' egoimageloader-%lu ' (unsigned long ) [savestring Hash]] withtimeoutinterval:24*60*60];

Read:
Copy Code code as follows:

NSString *getsavestring = [[Egocache globalcache] stringforkey:[nsstring stringwithformat:@ "EGOImageLoader-%lu", ( unsigned long) [@ "savestring" hash]]];

Does it feel similar to nsdictionary, indeed, we said earlier that Egocache is a key-value caching framework.

Cache UIImage with Egocache

Store:

Copy Code code as follows:

UIImage *saveimage = [uiimage imagenamed:@ "Iosdevtip"];
[[Egocache Globalcache] setimage:saveimage forkey:[nsstring stringwithformat:@ "Egoimageloader-%lu" (unsigned long) [ @ "SaveImage" Hash]] withtimeoutinterval:24*60*60];

Read:
Copy Code code as follows:

UIImage *getsaveimage = [[Egocache globalcache] imageforkey:[nsstring stringwithformat:@ "EGOImageLoader-%lu", ( unsigned long) [@ "SaveImage" hash]]];

cache NSData with Egocache

Store:

Copy Code code as follows:

NSData *savedata = [NSData data];
[[Egocache Globalcache] setdata:savedata forkey:[nsstring stringwithformat:@ "Egoimageloader-%lu" (unsigned long) [@] SaveData "Hash]] withtimeoutinterval:24*60*60];

Read:
Copy Code code as follows:

UIImage *getsavedata = [[Egocache globalcache] dataforkey:[nsstring stringwithformat:@ "EGOImageLoader-%lu" (unsigned Long) [@ "SaveData" hash]]];

Egocache how to detect cache time expiration
Egocache can set the cache expiration time by default of 1 days. Check the Egocache source code, set the default time:

Copy Code code as follows:

[Self setdefaulttimeoutinterval:86400];
86400 = 24 * 60 * 60 is just a day's time.

Egocache Why do you want to provide a set cache expiration time? Or what is the benefit of setting cache expiration times? I think the biggest advantage is that you can periodically clear the cache. You can set the cache time for an item, which makes it easy to manage caching.

So here's the question:

    • How does Egocache detect cache expiration time?
    • When the cache entry is triggered when the time expires is detected?

With these two questions, let's continue our analysis.

How are you going to make it

Remember in the company, the boss often give such an example:

Comrade So-and-So, when we first came to our company, we knew the complaint when we met the problem. Never know to think how to solve, only know to throw the problem to the leader. Work six months down, grow a lot. Now there are problems, not only throw out the problem, but also provide your own solutions ...
I believe we all have heard of similar examples. Similarly, since we have raised these two questions before, let's think about how we can solve them.

If I had to write it, there are a few ways to do it in my head:

    • The timer is used to poll, and is tested once every once in a while.
    • Write a while loop to detect.
    • Every time you read a cached item, you determine whether the cache time expires. Returns a read cache entry if it is not expired; otherwise, return nil.
    • Of course, there are some methods, no one by one cases are raised. Think about it, the drawbacks of these methods are easily revealed.

For small cache time, use the timer polling, is obviously a waste of resources
Similar to Method 1.
Every time you read the judge whether the expiration, if not read, the app's cache will become larger, nor desirable.
These methods have been ruled out, is there a good way? Keep looking down:

How did the Egocache come true?

Carefully look at the Egocache source code, found in the Initwithcachedirectory: method, each initialization Egocache instance object, will traverse the plist file in all existing cache entries, take the time of each cache entry and the current time for comparison, When the cache entry expires earlier than the current time, the corresponding cache file is deleted and the record of the corresponding key in the plist file is deleted.

The specific implementation code is as follows:

Reading cached Item Information

Copy Code code as follows:

_cacheinfo = [[Nsdictionary dictionarywithcontentsoffile:cachepathforkey (_directory, @ "EGOCache.plist")] Mutablecopy];
if (!_cacheinfo) {
_cacheinfo = [[Nsmutabledictionary alloc] init];
}

Get the nstimeinterval of the current time
Copy Code code as follows:

Nstimeinterval now = [[NSDate date] timeintervalsincereferencedate];

Declares Removedkeys to save expired cache entries corresponding to the key
Copy Code code as follows:

nsmutablearray* Removedkeys = [[Nsmutablearray alloc] init];

Traversing cache entry information and determining cache time
Copy Code code as follows:

For (nsstring* key in _cacheinfo) {
Determines whether the cache entry expires before the current time
if ([_cacheinfo[key] timeintervalsincereferencedate] <= now) {
To remove a cached item if the cache entry expires before the current time
[[Nsfilemanager Defaultmanager] Removeitematpath:cachepathforkey (_directory, key) Error:null];
Save expired cache entry for key to Removedkeys
[Removedkeys Addobject:key];
}
}

Key for deletion of expired cache entries
Copy Code code as follows:

[_cacheinfo Removeobjectsforkeys:removedkeys];

See these, is not think someone else's thinking special fork, anyway, I think this author is not simple. Is that the right move?

What else did Egocache do?

Careful child shoes will find that: Egocache is a Single-column class, that is, the entire application cycle of the program is initialized only once.

Copy Code code as follows:

+ (Instancetype) Globalcache {
static ID instance;

Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
instance = [[[Self class] alloc] init];
});
return instance;
}


It is correct to determine whether the cache entry expires each time it is initialized. Think of a scene:

The user opens the App,egocache is initialized and determines whether the cache entry expires.
If there is just a cache entry that expires after Egocache is initialized. This time we can still read this cache entry. That's not the right thing to do.
Continue to analyze Egocache source found, Egocache read a cache entry, first to determine if the cache entry exists, and then read the cache entry (Note: Read Egocache initialization without expired cache entries, and did not say that there is no expiration), Finally, determine if the cache entry is out-of-date compared to the current time.

Specifically implemented as follows:

Copy Code code as follows:

-(BOOL) Hascacheforkey: (nsstring*) Key {
No expired cache entries when reading Egocache initialization
nsdate* date = [self Dateforkey:key];
if (date = = nil) return NO;
Determines whether a read cache entry is currently out of date
if ([Date timeintervalsincereferencedate] < Cfabsolutetimegetcurrent ()) return NO;
return [[Nsfilemanager Defaultmanager] Fileexistsatpath:cachepathforkey (_directory, key)];
}
-(nsdate*) Dateforkey: (nsstring*) Key {
__block nsdate* date = nil;

Dispatch_sync (_frozencacheinfoqueue, ^{
Date = (self.frozencacheinfo) [key];
});

return date;
}


Egocache detection Cache time expired thinking is worth learning, and later encountered similar scenes, can be used for reference.

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.