这是我第一次使用NSCache
,我知道它不会在应用程序午餐中持续存在。
但是它会持续存在ViewControllers
吗?...意思是...如果我将其设置为cache object
打开ViewController A
然后移动到ViewController B
我仍然可以访问它吗?
我的问题与我在代码中遇到的问题有关。我在ViewController B
并且我设置了缓存对象。然后移动到ViewController B
并尝试检索该对象,但从未找到。
这是正常的还是我的代码有问题???我的视图非常便宜,所以我看不出它为什么会丢弃缓存对象
ViewController A(使用缓存)
- (void) searchDone:(NSDictionary*)response {
NSString * str = input.text;
str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString* cachedKey = [str stringByReplacingOccurrencesOfString:@"#" withString:@""];
cachedKey = [cachedKey lowercaseString];
//
// Cache
//
NSCache * cache = [[NSCache alloc]init];
NSDictionary* chachedData = [cache objectForKey:cachedKey];
// Check for a cached version of this
if ( chachedData ) {
NSLog(@"There is a cache");
NSTimeInterval timeDifferenceBetweenDates = [chachedData[@"time"] timeIntervalSinceNow];
CGFloat time = fabsf(timeDifferenceBetweenDates);
if ( time < sysTraditionalSearchCacheTime ) {
NSLog(@"using cache");
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:input.text,@"input",chachedData,@"response",nil];
[[NSNotificationCenter defaultCenter]
postNotificationName:@"closeSearch"
object:nil
userInfo:dictionary];
return;
}
[cache removeObjectForKey:cachedKey];
}
ViewController B(缓存设置器)
- (void) notificationCloseSearch:(NSNotification*) notification {
input.text = [[notification userInfo] valueForKey:@"input"];
NSDictionary* response = [[notification userInfo] valueForKey:@"response"];
NSString * str = input.text;
str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString* cachedKey = [str stringByReplacingOccurrencesOfString:@"#" withString:@""];
cachedKey = [cachedKey lowercaseString];
//
// Cache
//
NSCache * cache = [[NSCache alloc]init];
NSDictionary* chachedData = [cache objectForKey:cachedKey];
// Check for a cached version of this
if ( chachedData ) {
NSTimeInterval timeDifferenceBetweenDates = [chachedData[@"time"] timeIntervalSinceNow];
CGFloat time = fabsf(timeDifferenceBetweenDates);
if ( time >= sysTraditionalSearchCacheTime ) {
[cache removeObjectForKey:cachedKey];
}
} else { // if there is no cache then set one
NSLog(@"setting cache key %@",cachedKey);
NSDate* now = [NSDate date];
NSMutableDictionary* newResopnse = [[NSMutableDictionary alloc]initWithDictionary:response];
[newResopnse setObject:now forKey:@"time"];
response = [[NSDictionary alloc] initWithDictionary:newResopnse];
[cache setObject:response forKey:cachedKey];
NSLog(@"cached %@",[cache objectForKey:cachedKey]);
}
}