ibireme / YYCache

High performance cache framework for iOS.
MIT License
2.37k stars 505 forks source link

YYDiskCache在移除数据时是否与LRU策略相反了? #37

Closed everettjf closed 8 years ago

everettjf commented 8 years ago

你好,YYKVStorage.m 中获取最近访问数据时,是否应该使用 asc 而不是 desc。最近的时间值更大。使用 desc 导致每次移除时把最近使用的元素优先移除掉了。

- (BOOL)removeItemsToFitCount:(int)maxCount {
        items = [self _dbGetItemSizeInfoOrderByTimeDescWithLimit:perCount];
- (NSMutableArray *)_dbGetItemSizeInfoOrderByTimeDescWithLimit:(int)count {
    NSString *sql = @"select key, filename, size from manifest order by last_access_time desc limit ?1;";
    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];

测试代码如下:

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *docDir = [(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
        NSString *testDir = [docDir stringByAppendingPathComponent:@"testDir"];
        NSLog(@"testDir = %@", testDir);

        YYDiskCache *diskCache = [[YYDiskCache alloc]initWithPath:testDir inlineThreshold:0];
        diskCache.customFileNameBlock = ^(NSString *key){
            return [key stringByAppendingPathExtension:@"txt"];
        };

        [diskCache setObject:@"hello" forKey:@"1"];
        [diskCache setObject:@"world" forKey:@"2"];

        NSLog(@"total count : %@",@([diskCache totalCount]));
//        NSLog(@"key 1 = %@", [diskCache objectForKey:@"1"]);
//        usleep(1000000);
//        NSLog(@"key 2 = %@", [diskCache objectForKey:@"2"]);

        NSLog(@"key 2 = %@", [diskCache objectForKey:@"2"]);
        usleep(1000000);
        NSLog(@"key 1 = %@", [diskCache objectForKey:@"1"]);

        [diskCache trimToCount:1];
        NSLog(@"total count : %@",@([diskCache totalCount]));
        NSLog(@"key 1 = %@", [diskCache objectForKey:@"1"]);
        NSLog(@"key 2 = %@", [diskCache objectForKey:@"2"]);
    });

输出如下:

2016-03-28 00:47:00.696 YYCacheTest[55228:1046537] total count : 2
2016-03-28 00:47:00.697 YYCacheTest[55228:1046537] key 2 = world
2016-03-28 00:47:01.700 YYCacheTest[55228:1046537] key 1 = hello
2016-03-28 00:47:01.701 YYCacheTest[55228:1046537] total count : 1
2016-03-28 00:47:01.701 YYCacheTest[55228:1046537] key 1 = (null)
2016-03-28 00:47:01.702 YYCacheTest[55228:1046537] key 2 = world

在最近访问 key1之后,应该优先移除 key2。但目前是移除了key1的值。

ibireme commented 8 years ago

哦。。是的。。这个地方错了。

everettjf commented 8 years ago

夜猫子啊,刚弄了个PullRequest……

ibireme commented 8 years ago

Fixed: https://github.com/ibireme/YYCache/pull/38