ios - 调用 NSCashe 不起作用

标签 ios nscache

我不知道如何使用NSCashe,但在阅读本主题后我已经尝试过了How to use NSCache但它没有用。

我遇到这个问题原因:'-[NSCache setObject:forKey:cost:]: attempt to insert nil value (key: indexPath)'

我做错了什么吗?

.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"];

        });
    });
}

最佳答案

您正在初始化 jsonArray1,就在设置它之前。

 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"

在那个教程中,他们说的是

  • 要设置一个值,请使用以下行:

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

  • 要检索值,请使用以下行。当您想使用该缓存值时,应使用此行

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

在你的情况下,只需评论

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

行并再次运行。它不会给出那个错误。

关于ios - 调用 NSCashe 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18014080/

相关文章:

ios - 检查 iOS 上的 NSCache 内容?

iOS 内存警告

ios - 设置AVCaptureDevice格式范围

ios - 在 iPhone 模拟器中关闭声音

ios - 最后一个 UITableViewCell 上的分隔符没有添加?

swift - 当滚动甚至存储在 NSCache 中时,UIImage 一直保持加载 - swift

ios - NSCache 是否跨 ViewControllers 持久存在?

objective-c - NSCache:尝试访问缓存项时总是得到 "not key value coding-compliant"

ios - 尝试使用 NSUrl(fileURLWithPath) 捕捉

ios - UIImageView+AFNetworking 获取URL的UIImage