Tuesday, May 7, 2013

NSCache setObject example ios


setObject :forKey:

Sets the value of the specified key in the cache.
- (void)setObject:(id)obj forKey:(id)key
Parameters
obj
The object to be stored in the cache.
key
The key with which to associate the value.
Discussion of [NSCache setObject]
Unlike an NSMutableDictionary object, a cache does not copy the key objects that are put into it.
Example of [NSCache setObject]

id object = [NSString stringWithFormat:@"%lu", theIndex % 10];
id key = [NSString stringWithFormat:@"sdffffffff%lu", theIndex];
[self.cache setObject :object forKey:key];
Example of [NSCache setObject]
// 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];
}