【问题标题】:Category + lazy instantiation patterns on Objective CObjective C 上的类别 + 惰性实例化模式
【发布时间】:2014-04-24 10:39:33
【问题描述】:

我正在尝试对一个类别使用惰性实例化,但我一直坚持如何在不进入明显无限循环的情况下做到这一点。这里有一些 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

有什么想法可以解决这种情况还是我根本不应该这样做?

【问题讨论】:

  • Usercache 属性吗?
  • 我认为我们必须这样假设,但问题并没有说明这一点。
  • 是的,用户有缓存属性,Martin R 接受的答案解决了这个问题。

标签: ios objective-c design-patterns cocoa-design-patterns


【解决方案1】:

为了避免 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;
}

类似的例子可以在“Core Data Programming Guide”和 "Custom Section Titles with NSFetchedResultsController" 示例项目的sectionIdentifier 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多