Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/103.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 类别+;目标C上的惰性实例化模式_Ios_Objective C_Design Patterns_Cocoa Design Patterns - Fatal编程技术网

Ios 类别+;目标C上的惰性实例化模式

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 *

我试图在一个类别上使用一个惰性实例化,但我一直在研究如何在不进入明显的无限循环的情况下实现它。下面是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

你知道如何解决这种情况吗?或者我应该干脆不这样做吗?

为了避免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的公认答案解决了问题。