Shravan
Shravan

Reputation: 438

store key/value in NSDictionary/NSCache which retains data till the app is terminated

I have an app where i want to create a temporary cache which stores key and value.I have done the following

My code is : IN appDelegate.h

@property (strong, nonatomic) NSMutableDictionary *articleCache;

In appDelegate.m

@synthesize articleCache;

and i am calling it in viewController.m here i need to store the data so that it is cleared only when the app is terminated and is accessible anywhere in the app otherwise. every time i visit an article i add it to the array so that next time i wont have to fetch it from the network thereby speed up the process.

the Problem is when i set the temp NSMutableDictionary the content gets added but for checkCache.articleCache i get nil.

#define DELEGATE ((AppDelegate*)[[UIApplication sharedApplication]delegate])

this is my viewDidLoad method:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //[self loadfeeds];
    [self.activityIndi startAnimating];
    AppDelegate *checkCache = DELEGATE;
    NSString *link = self.webUrl;

//check if the article is already opened and cached before

    if([[checkCache.articleCache allKeys] containsObject:link])
    {
        NSLog(@"Key Exists");
        NSString *contents = [checkCache.articleCache valueForKey:link];
        [self loadDataOnView:contents];
    }
    else
    {
        NSOperationQueue* aQueue = [[NSOperationQueue alloc] init];
        [aQueue addOperationWithBlock:^{
            NSLog(@"Key not Exists");
            [self startParsing];
        }];
    } 
}

In parser method at the end i do the following i.e to store the article.. but if i add it directly to the checkCache.articleCache nothing is added what should i do?? but it gets added to temp.. do i access the articleCache incorrectly??

AppDelegate *checkCache = DELEGATE;
NSMutableDictionary *temp = [[NSMutableDictionary alloc] init];
    [checkCache.articleCache setObject:Content forKey:url];
    [temp setObject:Content forKey:url];

So how can i solve it?? or Suggest me how can i use NSCache for the same problem. thanks a lot. It might be a silly question but i m quite new to ios thanks.

Upvotes: 0

Views: 542

Answers (1)

Ankit Srivastava
Ankit Srivastava

Reputation: 12405

In App delegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.articleCache = [NSMutableDictionary new];
return YES;
}

When you have to set the object in cache.

AppDelegate *checkCache = DELEGATE;
[checkCache.articleCache setObject:obj forKey:@"Key1"];

To get the object back:

AppDelegate *checkCache = DELEGATE;
id obj = [checkCache.articleCache objectForKey:@"Key1"];

Though there are better ways to get this done.

Upvotes: 1

Related Questions