Tuesday, May 7, 2013

NSCache countLimit example ios


countLimit

Returns the maximum number of objects that the cache can currently hold.
- (NSUInteger)countLimit
Return Value
The maximum number of objects that the cache can currently hold.
Discussion of [NSCache countLimit]
By default, countLimit will be set to 0. Any countLimit less than or equal to 0 has no effect on the number of allowed entries in the cache. This limit is not a strict limit, and if the cache goes over the limit, an object in the cache could be evicted instantly, later, or possibly never, all depending on the implementation details of the cache.
Example of [NSCache countLimit]


- (NSCache *)imageCache {

    if (!_imageCache) {
        _imageCache = [[NSCache alloc] init];
        _imageCache.countLimit = kIMAGE_REQUEST_CACHE_LIMIT;
    }
    return _imageCache;
}
Example of [NSCache countLimit]
-(UIImage *)buscarEnCache:(UsersController *)auxiliarStruct{
    UIImage *image;

    NSLog(@"cache: %i", [cache countLimit]);
    if ([cache countLimit] > 0) {
        if ([cache objectForKey:auxiliarStruct.thumb]){    
            image = [cache objectForKey:auxiliarStruct.thumb];
        }else{ //IF isnt't cached, is saved
            NSString *imageURLString = [NSString stringWithFormat:@"http://mydomain.com/%@",auxiliarStruct.thumb];
            NSURL *imageURL = [NSURL URLWithString:imageURLString];
            NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
            image = [UIImage imageWithData:imageData];
            [cache setObject:image forKey:auxiliarStruct.thumb];
        }        
    }else{ 
        NSString *imageURLString = [NSString stringWithFormat:@"http://mydomain.com/%@",auxiliarStruct.thumb];
        NSURL *imageURL = [NSURL URLWithString:imageURLString];
        NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
        image = [UIImage imageWithData:imageData];
        [cache setObject:image forKey:auxiliarStruct.thumb];
    }
    return image;
}