我有一个应用程序,我想在其中创建一个存储键和值的临时缓存。我已经完成了以下操作
我的代码是:IN appDelegate.h
@property (strong, nonatomic) NSMutableDictionary *articleCache;
在 appDelegate.m 中
@synthesize articleCache;
我在 viewController.m 中调用它 在这里,我需要存储数据,以便仅在应用程序终止时才清除数据,否则可以在应用程序中的任何位置访问数据。 每次我访问一篇文章时,我都会将其添加到数组中,这样下次我就不必从网络中获取它,从而加快进程。
问题是当我设置临时 NSMutableDictionary 时,内容被添加,但对于 checkCache.articleCache 我得到 nil。
#define DELEGATE ((AppDelegate*)[[UIApplication sharedApplication]delegate])
这是我的 viewDidLoad 方法:
- (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];
}];
}
}
在最后的解析器方法中,我执行以下操作,即存储文章.. 但如果我直接将其添加到 checkCache.articleCache 中,则不会添加任何内容,我该怎么办?但它被添加到临时文件中..我是否错误地访问了articleCache??
AppDelegate *checkCache = DELEGATE;
NSMutableDictionary *temp = [[NSMutableDictionary alloc] init];
[checkCache.articleCache setObject:Content forKey:url];
[temp setObject:Content forKey:url];
那我该如何解决呢? 或者建议我如何使用 NSCache 来解决同样的问题。多谢。 这可能是一个愚蠢的问题,但我对 ios 很陌生,谢谢。
最佳答案
在应用委托(delegate)中:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.articleCache = [NSMutableDictionary new];
return YES;
}
当你必须在缓存中设置对象时。
AppDelegate *checkCache = DELEGATE;
[checkCache.articleCache setObject:obj forKey:@"Key1"];
要取回对象:
AppDelegate *checkCache = DELEGATE;
id obj = [checkCache.articleCache objectForKey:@"Key1"];
尽管有更好的方法来完成这项工作。
关于ios - 将键/值存储在 NSDictionary/NSCache 中,它保留数据直到应用程序终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34852826/