Luai Kalkatawi
Luai Kalkatawi

Reputation: 1492

Calling NSCashe doesn't work

I don't know how to use NSCashe but I have tried it after reading this topic How to use NSCache but it didn't work.

I am getting this issue reason: '-[NSCache setObject:forKey:cost:]: attempt to insert nil value (key: indexPath)'

Am I doing something wrong?

.h

@interface ViewController : UIViewController

@property (nonatomic, strong) NSMutableArray *jsonArray;

@property (nonatomic, strong) NSMutableArray *jsonArray1;

@property (nonatomic, retain) NSCache *Cache;

.m

- (void)viewDidLoad
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSData *response = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://kalkatawi.com/jsonTest.php"]];
        NSError *parseError = nil;
        jsonArray = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&parseError];
        jsonArray1 = [[NSMutableArray alloc] init];
        Cache = [[NSCache alloc]init];
        for(int i=0;i<[jsonArray count];i++)
        {
            NSString  * city = [[jsonArray objectAtIndex:i] objectForKey:@"city"];

            [jsonArray1 addObject:city];
        }

        dispatch_sync(dispatch_get_main_queue(), ^{

            self.title = @"İller";

            [self.mytable1 reloadData];

            jsonArray1 = [Cache objectForKey:@"indexPath"];

            [Cache setObject:jsonArray1 forKey:@"indexPath"];

        });
    });
}

Upvotes: 2

Views: 261

Answers (1)

Mrunal
Mrunal

Reputation: 14118

you are initializing jsonArray1, just before setting it up.

 jsonArray1 = [Cache objectForKey:@"indexPath"]; // here jsonArray1 = nil; hence remove this line and run your code again. Yo

 [Cache setObject:jsonArray1 forKey:@"indexPath"]; // hence you are setting nil value to this key "indexpath"

In that tutorial they are saying like

  • To set a value use following line:

[Cache setObject:jsonArray1 forKey:@"indexPath"];

  • To retrieve a value use following line. This line should be used when you want to used that cached value

jsonArray1 = [Cache objectForKey:@"indexPath"];

In your case, just comment

jsonArray1 = [Cache objectForKey:@"indexPath"];

line and run again. It will not give that error.

Upvotes: 1

Related Questions