Ios 类别+;目标C上的惰性实例化模式
我试图在一个类别上使用一个惰性实例化,但我一直在研究如何在不进入明显的无限循环的情况下实现它。下面是ilustrate的一些代码:Ios 类别+;目标C上的惰性实例化模式,ios,objective-c,design-patterns,cocoa-design-patterns,Ios,Objective C,Design Patterns,Cocoa Design Patterns,我试图在一个类别上使用一个惰性实例化,但我一直在研究如何在不进入明显的无限循环的情况下实现它。下面是ilustrate的一些代码: @implementation User (Extras) - (CacheControl *)cache { CacheControl *_cache = (CacheControl *)[self valueForKey:@"cache"]; if(!_cache){ [self setCache:(CacheControl *
@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
你知道如何解决这种情况吗?或者我应该干脆不这样做吗?为了避免getter方法中的无限递归,你必须使用 “基本访问器”核心数据访问器方法:
- (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;
}
类似的例子可以在“核心数据编程指南”和中找到
示例项目的
sectionIdentifier
方法。User是否具有cache
属性?我认为我们必须假设这样,但问题没有明确说明。是的,用户具有cache属性,Martin R的公认答案解决了问题。