这是我第一次使用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]);
}
}
答案 0 :(得分:2)
NSCache是某种NSMutableDictionary。 不同之处在于,当NSCache检测到过大的内存压力时,它会释放一些键值对。 在ViewControllerA中,您可以创建NSCache对象
NSCache * cache = [[NSCache alloc]init];
在ViewControllerB中,再次创建一个NSCache对象
NSCache * cache = [[NSCache alloc]init];
因此它将是两个不同的对象,具有两组不同的键值对。 如果你需要某种存储,你可以编写一个包含一个NSCache对象的单例类。