1

初めて使用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]);
    }
}
4

1 に答える 1