NSCache的用法

2018-01-04  本文已影响14人  木兮_君兮

是什么

NSCache 是一个类似NSDictionary的工具,当内存警告的时候,他会自动释放。

-源码

@interface NSCache <KeyType, ObjectType> : NSObject {
@private
    id _delegate;
    void *_private[5];
    void *_reserved;
}

@property (copy) NSString *name;

@property (nullable, assign) id<NSCacheDelegate> delegate;

- (nullable ObjectType)objectForKey:(KeyType)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;    // limits are imprecise/not strict
@property NSUInteger countLimit;    // limits are imprecise/not strict
@property BOOL evictsObjectsWithDiscardedContent;

@end

@protocol NSCacheDelegate <NSObject>
@optional
- (void)cache:(NSCache *)cache willEvictObject:(id)obj;
@end

做什么

拿来可以做性能优化,可以做缓存,搭配本地数据库,在恰当的时候对数据做恰当的处理。

怎么做

1. 初始化 (NSCache)
2. 数据操作:- setObject:forKey: (写)
           - objectForKey:(读) 
上一篇下一篇

猜你喜欢

热点阅读