重新启动项目后,NSCache返回null

时间:2014-11-07 14:41:18

标签: ios objective-c nscache

我在Objective-C和Cocoa for iOS中使用NSCache。每次重新启动项目时,getCacheRecommend调用都会返回null,我希望它返回一个值。

#import <Foundation/Foundation.h>
@class ASJsonDiscoverModel;
@interface ASUserCache : NSObject

+ (ASUserCache *)sharedInstance;    
- (void)clear;
- (void)setCacheRecommend:(ASJsonDiscoverModel *)discover;
- (ASJsonDiscoverModel *)getCacheRecommend;

ASJsonDiscoverModel是我的自定义对象类。

#import "ASUserCache.h"
@interface ASUserCache ()
@property (nonatomic,strong) NSCache *cache;
@end

@implementation ASUserCache

+ (ASUserCache *)sharedInstance
{
    __strong static ASUserCache *cache = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        cache = [[ASUserCache alloc] init];
    });
    return cache;
}

- (instancetype)init
{
    if (self = [super init]) {
         _cache = [[NSCache alloc] init];
    }
    return self;
}

- (void)setCacheRecommend:(ASJsonDiscoverModel *)discover
{
    NSString *key = @"channelRecommend";
    [_cache removeObjectForKey:key];
    [_cache setObject:discover forKey:key];
}

- (ASJsonDiscoverModel *)getCacheRecommend
{
    NSString *key = @"channelRecommend";
    return [_cache objectForKey:key];
}

- (void)clear
{
    if (_cache) {
        [_cache removeAllObjects];
    }
}

- (NSString *)keyforUserID:(NSString *)userID
{
    return [NSString stringWithFormat:@"**%@",userID];
}

0 个答案:

没有答案