NSCache的使用

2018-05-14  本文已影响35人  浪淘沙008

- (nullableObjectType)objectForKey:(KeyType)key;  //根据key取出某条数据

- (void)setObject:(ObjectType)obj forKey:(KeyType)key;// 0 cost    //添加某条数据

- (void)setObject:(ObjectType)obj forKey:(KeyType)key cost:(NSUInteger)g;  //添加某条数据并设置其占用的资源数目

- (void)removeObjectForKey:(KeyType)key;    //删除某条数据

- (void)removeAllObjects;  //删除所有数据

@property NSUInteger totalCostLimit; // 设置缓存大小限制

@property NSUInteger countLimit; // 设置总条数的限制

@property BOOL evictsObjectsWithDiscardedContent;   //是否自动舍弃那些内存已经被丢弃的对象

- (void)cache:(NSCache *)cache willEvictObject:(id)obj;   //代理方法当对象呗删除时调用


//将对象数组保存到cache中

- (void)addDataArr:(NSArray*)dataArr modelStr:(NSString*)str {

    if(dataArr.count==0)return;

    for(NSIntegeri =0; i < dataArr.count; i++) {

        [self.cache setObject:dataArr[i] forKey:[NSString stringWithFormat:@"%@%ld", str,i] cost:1]; 

    }

}

//根据对应的字符串取出缓存数据

- (NSArray*)getDataWithModelStr:(NSString*)str {

    NSMutableArray * dataArr = @[].mutableCopy;

    for(NSIntegeri =0; i <self.cache.countLimit; i++) {

        NSObject * model = [_cache objectForKey:[NSString stringWithFormat:@"%@%ld", str,i]];

        if(model) {

            [dataArraddObject:model];

        }else{

            break;

        }

    }

    returndataArr;

}

//根据key值删除对应的缓存数据

- (void)removeObjectForKey:(NSString*)key

{

    for(NSIntegeri =0; i

        id model = [_cache objectForKey:[NSString stringWithFormat:@"%@%ld", key,i]];

        if(model) {

            [self.cache removeObjectForKey:[NSString stringWithFormat:@"%@%ld", key,i]];

        }else{

            return;

        }

    }

}

//删除所有数据

- (void)removeAllObjects

{

    [self.cache removeAllObjects];

}

上一篇 下一篇

猜你喜欢

热点阅读