Tuesday, May 7, 2013

NSCache objectForKey example ios


objectForKey:

Returns the value associated with a given key.
- (id)objectForKey:(id)key
Parameters
key
An object identifying the value.
Return Value of [NSCache objectForKey]
The value associated with key, or NULL if no value is associated with key. The caller does not have to release the value returned to it.
Example of [NSCache objectForKey]
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:1];
 NSString *res = [cache objectForKey :indexPath];
 if (!res) {                      
     res=@"1";
     [cache setObject:res forKey:indexPath];
 }
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:1];
NSLog(@"%@",[cache objectForKey:indexPath]);
Example of [NSCache objectForKey]
// Your cache should have a lifetime beyond the method or handful of methods
// that use it. For example, you could make it a field of your application
// delegate, or of your view controller, or something like that. Up to you.
NSCache *myCache = ...;
NSAssert(myCache != nil, @"cache object is missing");

// Try to get the existing object out of the cache, if it's there.
Widget *myWidget = [myCache objectForKey: @"Important Widget"];
if (!myWidget) {
    // It's not in the cache yet, or has been removed. We have to
    // create it. Presumably, creation is an expensive operation,
    // which is why we cache the results. If creation is cheap, we
    // probably don't need to bother caching it. That's a design
    // decision you'll have to make yourself.
    myWidget = [[[Widget alloc] initExpensively] autorelease];

    // Put it in the cache. It will stay there as long as the OS
    // has room for it. It may be removed at any time, however,
    // at which point we'll have to create it again on next use.
    [myCache setObject: myWidget forKey: @"Important Widget"];
}

// myWidget should exist now either way. Use it here.
if (myWidget) {
    [myWidget runOrWhatever];
}