0

I'm working with NSCache in Objective-C and Cocoa for iOS. Every time I restart the project, the getCacheRecommend call returns null and I expect it to return a value.

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

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

ASJsonDiscoverModel is my custom object class.

#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];
}
Ryan Ransford
  • 3,224
  • 28
  • 35

0 Answers0