Skip to content

Instantly share code, notes, and snippets.

@Kentzo
Created July 31, 2011 11:39
Show Gist options
  • Select an option

  • Save Kentzo/1116722 to your computer and use it in GitHub Desktop.

Select an option

Save Kentzo/1116722 to your computer and use it in GitHub Desktop.
How to use NSCache right.
NSCache cache = [[NSCache alloc] init];
/*
...
*/
// WRONG
id o = [cache objectForKey:ObjectKey];
if (o == nil)
{
o = /* create object by alloc init… */;
[cache setObject:o forKey:ObjectKey];
NSAssert([cache objectForKey:ObjectKey] != NULL, @"NSCache may release o here!");
[o release];
}
return o;
// RIGHT
id o = [cache objectForKey:ObjectKey];
if (o == nil)
{
o = /* create object by alloc init… */;
[o autorelease];
[cache setObject:o forKey:ObjectKey];
}
return o;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment