iosobjective-cdesign-patternscocoa-design-patterns

Category + lazy instantiation patterns on Objective C


I'm trying to use a lazy instantiation on a category but I'm stuck on how to do that without enter in a obvious infinity loop. Here some code for ilustrate:

@implementation User (Extras)

- (CacheControl *)cache
{
    CacheControl *_cache = (CacheControl *)[self valueForKey:@"cache"];
    if(!_cache){
        [self setCache:(CacheControl *)[NSEntityDescription insertNewObjectForEntityForName:@"CacheControl" inManagedObjectContext:self.managedObjectContext]];
    }
    return _cache;
}
@end

Any Ideas how to address this situation or should I just don't do that at all?


Solution

  • To avoid infinite recursion in the getter method, you have to use the "primitive accessor" Core Data accessor methods:

    - (CacheControl *) cache {
        [self willAccessValueForKey:@"cache"];
        CacheControl * cache = [self primitiveValueForKey:@"cache"];
        [self didAccessValueForKey:@"cache"];
    
        if (cache == nil) {
            cache = [NSEntityDescription insertNewObjectForEntityForName:@"CacheControl" inManagedObjectContext:self.managedObjectContext];
            [self setPrimitiveValue:cache forKey:@"cache"];
        }
        return cache;
    }
    

    Similar examples can be found in the "Core Data Programming Guide" and in the sectionIdentifier method of the "Custom Section Titles with NSFetchedResultsController" sample project.