Giter Site home page Giter Site logo

egocache's Introduction

EGOCache

EGOCache is a simple, thread-safe key value cache store for macOS, iOS, tvOS and watchOS.

It has native support for NSString, UIImage, NSImage, and NSData, but can store anything that implements <NSCoding>. All cached items expire after the timeout, which by default, is one day.

Installation

Carthage

github "enormego/EGOCache" ~> 2.2.0

CocoaPods

pod 'EGOCache', '~> 2.2.0'

Without a dependency manager

Drag EGOCache.h and EGOCache.m into your project.

License

Copyright (c) 2017 enormego

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

egocache's People

Contributors

adamjernst avatar bm-i avatar dmitric avatar eyeplum avatar fannheyward avatar ferlatte avatar jfradj avatar jpm avatar lukeredpath avatar mbkwon avatar oriolblanc avatar shnhrrsn avatar shuding avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

egocache's Issues

Handle cache in diskOperation

would you like to handle cache in disk operation?
You know some code like above-

  • (NSData_)dataForKey:(NSString_)key {
    if([self hasCacheForKey:key]) {
    return [NSData dataWithContentsOfFile:cachePathForKey(key) options:0 error:NULL];
    } else {
    for(NSInvocationOperation* operation in [diskOperationQueue operations]){
    NSInvocation *invocation=[operation invocation];
    NSString *path=nil;
    NSData *data=nil;
    [invocation getArgument:&path atIndex:3];
    if([path hasSuffix:key]){
    [invocation getArgument:&data atIndex:2];
    return data;
    }
    }
    return nil;
    }
    }

Cache verify

Hello,

In my project I add the block in - (UIImage_)imageForKey:(NSString_)key { :
if (!image && pathImage){
@Try {
NSData *data = [NSData dataWithContentsOfFile:pathImage];
image = [UIImage imageWithData:data];
} @catch (NSException *e1) {

        }
    }

if not success "[NSKeyedUnarchiver unarchiveObjectWithFile:pathImage]", then verify if can transform the data file in UIImage;

It's working very fine.

Can you add this in the project? Because I'm using cocoaPods in my project.

Thank you! This Class is wonderful.

  • (UIImage_)imageForKey:(NSString_)key {
    UIImage* image = nil;
    NSString _pathImage = nil;
    @Try {
    pathImage = cachePathForKey(directory, key);
    image = [NSKeyedUnarchiver unarchiveObjectWithFile:pathImage];
    } @catch (NSException
    e) {
    // Surpress any unarchiving exceptions and continue with nil
    if (!image && pathImage){
    @Try {
    NSData *data = [NSData dataWithContentsOfFile:pathImage];
    image = [UIImage imageWithData:data];
    } @catch (NSException *e1) {

        }
    }
    

    }

    return image;
    }

compile error.

EGOCache.m:328:61: error: no visible @interface for 'NSImageRep' declares the selector 'representationUsingType:properties:'
[self setData:[[[anImage representations] objectAtIndex:0] representationUsingType:NSPNGFileType properties:nil] forKey:key withTimeoutInterval:timeoutInterval];
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.

Xcode Version 8.3.3 (8E3004b)
OSX 10.12.5

Cache increase capacity folder

I use EGO cache and check cache folder, i download 5 images with total: 1,2mb and see cache files, capacity of cache folder is 6mb... What happen? Please, Can you explain it?

Disk caches should be done asynchronously

Writing to disk can be a severe performance bottleneck if you are doing some caching whilst performing some other intensive operation (e.g. image caching using EGOImageLoading whilst scrolling a table view).

Whilst I've had several performance issues with EGOImageLoading and UITableViews I've narrowed this down as one of the major culprits.

Ideally disk-reads would be done asynchronously too but this would make the API more complicated; any suggestions?

Crash on [EGOCache saveCacheDictionary]

App crash on EGOCache.m line 208 [EGOCache saveCacheDictionary].

Fatal Exception
*** Collection <__NSCFDictionary: 0x1e066e00> was mutated while being enumerated.

Memory cache versus disk cache

Is it possible to cache it in memmory also? I know that EGOCache will cache in disk, but Im using a uitableview and I would like to cache also in memory, to make scrolling the uitableview smooth. Any ideas? Suggestions?

EGOCache should use Library/Caches directory

EGOCache currently stores its data under APP_HOME/Documents/EGOCache which means the cache gets backed up by iTunes. Most of the time, this probably isn't what you want (as the data can easily be recreated) and probably only increases user backup times if your cache is quite big.

Apple recommends using the APP_HOME/Library/Caches folder as this is not backed up by iTunes but is persisted between application launches.

Files and Networking documentation

dispatch_set_target_queue usage not correct

In initWithCacheDirectory method of EGOCache.m file, the dispatch_set_target_queue's usage is not correct.

- (instancetype)initWithCacheDirectory:(NSString*)cacheDirectory {
    if((self = [super init])) {
        _cacheInfoQueue = dispatch_queue_create("com.enormego.egocache.info", DISPATCH_QUEUE_SERIAL);
        dispatch_queue_t priority = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
        dispatch_set_target_queue(priority, _cacheInfoQueue);

        _frozenCacheInfoQueue = dispatch_queue_create("com.enormego.egocache.info.frozen", DISPATCH_QUEUE_SERIAL);
        priority = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
        dispatch_set_target_queue(priority, _frozenCacheInfoQueue);

        _diskQueue = dispatch_queue_create("com.enormego.egocache.disk", DISPATCH_QUEUE_CONCURRENT);
        priority = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
        dispatch_set_target_queue(priority, _diskQueue);

In man page of dispatch_set_target_queue, it has below statements:

The result of passing the main queue or a global concurrent queue as the first argument of dispatch_set_target_queue() is undefined.

So the usage of dispatch_set_target_queue is not correct, the correct usage should be as below:

dispatch_set_target_queue(_cacheInfoQueue, priority);
dispatch_set_target_queue(_frozenCacheInfoQueue, priority);
dispatch_set_target_queue(_diskQueue, priority);

Can't restore image from cache (iOS)

The method - (UIImage_)imageForKey:(NSString_)key returns nil every time.
After evaluating next string the image is still nil, but image actually is cached.
image = [NSKeyedUnarchiver unarchiveObjectWithFile:cachePathForKey(_directory, key)];
Where is the bug? Who knows?

DataFromPropertyList: is deprecated

From a project I'm working on. Should be a simple fix. Assign to me if necessary

'propertyListFromData:mutabilityOption:format:errorDescription:' is deprecated: first deprecated in iOS 8.0 - Use propertyListWithData:options:format:error: instead.

Clear the cache does not work

It's seem that [[EGOCache globalCache] clearCache] doesn't work at all. The cache is still there. The images are loaded using the cache, not downloading again after this method is called. Please consider this.

Update: I changed all the currentCache method in the lib to globalCache then it works, but not perfectly.
It doesn't work at all in iOS 6.1 but sometimes work in iOS5.1. For details, the first time the clear cache button is pressed, it works. But then it sometimes just doesn't work, or some images are still cached, while some others are cleared.

Using paths as keys

As it is, It's not possible to use path as key because directories contained in path doesn't exists.

maybe something like this may fix the issue

  • (void)writeData:(NSData*)data toPath:(NSString *)path; {
    [[NSFileManager defaultManager] createDirectoryAtPath:[[path stringByExpandingTildeInPath] stringByDeletingLastPathComponent]
    withIntermediateDirectories:YES
    attributes:nil
    error:nil];
    [data writeToFile:path atomically:YES];
    }

I don't wanted to alter the original file (thus I can update it without asking me if I had to merge any modifications) so I changed my keys by replacing path separator by # ;-)

Cheers.

get cache created at NSDate

add a method that allows to get the date when the cache was created.

- (NSDate*) getCreatedAt:(NSString*)key;

It will then allow to use this logic.

if has cachedData
    load from cachedData
    if cachedCreateDate is old
        fetch online, cache it and reload
else
    fetch online, cache it and load

I want to set the cache as long as possible, but if it is old I would like to load from cache and fetch online too.

problem while unarchive cached object

line 289 in EGOCache.m method - (UIImage*)imageForKey:(NSString*)key.
[NSKeyedUnarchiver unarchiveObjectWithFile:cachePathForKey(_directory, key)] return nil and throw a exception:
*** -[NSKeyedUnarchiver initForReadingWithData:]: incomprehensible archive (0xffffffff, 0xffffffd8, 0xffffffff, 0xffffffe0, 0x0, 0x10, 0x4a, 0x46)
Does anyone else have this problem? I got this problem while using EGOImageLoading.

Old key entries are never removed from cache dictionary plist

So I'm debugging memory usage in one of my client's apps, and I ended up reviewing how EGOCache is keeping track of its objects. In the init method there's this interesting little bit of code:

    for(NSString* key in cacheDictionary) {
        NSDate* date = [cacheDictionary objectForKey:key];
        if([[[NSDate date] earlierDate:date] isEqualToDate:date]) {
            [[NSFileManager defaultManager] removeItemAtPath:cachePathForKey(key) error:NULL];
        }
    }

It's interesting to me because the code seems to be checking the entries in the EGOCache.plist file, and seeing if there are entries there that have the date object being older than "right now". If so, remove the cache file from disk.

Seems perfect, however the cache dictionary entry itself is still kept, so the EGOCache.plist file keeps growing and growing. I have a file that has been around for a while, with close to 10,000 entries in the plist file. Most of the entries have dates in 2011.

Is there a reason for not deleting these cache dictionary entries? I'm assuming it's just something being overlooked, but wanted to check before modifying the code to fix this.

--Joao

Caching an Array?

Wondering how I could cache an array of a feed's items that I'm pulling in.

This is what I have:

// Cached Information
NSArray *cachedArray = [NSArray arrayWithContentsOfFile:[[EGOCache currentCache] dataForKey:@"newsCacheKey"]];

//If nothing loaded (there was nothing saved)
if (cachedArray == nil) {

    // Begin parsing
    self.view = featuredTableView;
    featuredTableView.hidden = NO;
    [feedParser parse];

}

//Or if something actually did load
else {
    self.itemsToDisplay = cachedArray;
}

Removing a cached object by key is not always possible

There seems to be a missing feature here somewhere related to EGOCache and EGOImageView. The use case is to force the removal of a cached image object from the system. The image itself was initially retrieved and cached with EGOImageView, but perhaps the image has been changed and the cached one is not valid anymore.

There's a handy [-EGOCache removeCacheForKey:] method which takes in a key string (image URL), but that URL doesn't match up with the internal representation of the key, since EGOImageLoader uses a static method keyForURL() to generate a better key name.

I was able to hack around this by copying the keyForURL method into my own file to get the internal version of the cache key, but that's ugly and nasty. The real fix is to provide a method to remove an image from the cache somehow.

Let me know if I'm missing something obvious here.

--Joao

Unproper usage of dispatch_queue_t ?

In initWithCacheDirectory:cacheDirectory method use dispatch_set_target_queue(priority, _cacheInfoQueue) code to set priority for _cacheInfoQueue, but according to Apple Developer, this should be dispatch_set_target_queue( _cacheInfoQueue, priority), I think here have a mistake.

pod 2.1.3 for iOS 8.3

Is there a pod 'EGOCache', '>= 2.1.3' for iOS 8.3
Nullability specifier '__nonnull' cannot be applied to non-pointer type 'NSString'; did you mean to apply the specifier to the pointer?

Flickering bug in tableview.

Still trying to figure out if it's just EGOCache since I've updated several libs (JSONKit, AFNetworking) But I think it's EGOCache related

Update tag

Cocoapods is pointing to 2.0 version that include a little bug related to a superflous autorelease.
Please create a new tag version pointing to a newer commit so that EGOCache can work on Cocoapods. I will take care to update the cocoaspec if necessary.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.