Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/25.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
Objective c 使用ARC在self.managedObjectContext上调用perfromBlock时是否保留循环?_Objective C_Memory Management_Automatic Ref Counting_Retain Cycle - Fatal编程技术网

Objective c 使用ARC在self.managedObjectContext上调用perfromBlock时是否保留循环?

Objective c 使用ARC在self.managedObjectContext上调用perfromBlock时是否保留循环?,objective-c,memory-management,automatic-ref-counting,retain-cycle,Objective C,Memory Management,Automatic Ref Counting,Retain Cycle,在下面的代码中,我是否正确理解了保留周期问题,是否会有保留周期 - (NSError *)importRoute:(NSDictionary *)route { [self.importContext performBlockAndWait:^{ [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:self.importContext];

在下面的代码中,我是否正确理解了保留周期问题,是否会有保留周期

- (NSError *)importRoute:(NSDictionary *)route {
    [self.importContext performBlockAndWait:^{
        [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:self.importContext];
        //do I get a retain cycle here?
    }];
    ...
}

- (NSManagedObjectContext *)importContext {
    if (!_importContext) {
        id appDelegate = [[UIApplication sharedApplication] delegate];
        _importContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        _importContext.parentContext = [appDelegate managedObjectContext];
    }
    return _importContext;
}

有一个保留周期,但它是暂时的。这是保留周期:

  • self
    保留
    importContext
  • importContext
    保留该块
  • 块保留
    self
块执行完成后,
importContext
将其释放。此时,块的保留计数变为零,并将其释放。当解除分配时,它将释放
self


通常,仅当块无限期保留时,涉及块的保留周期才是一个问题,例如,因为您将其存储在属性、实例变量或容器中。如果您只是将一个块传递给将在不久的将来执行一次该块的函数,那么您通常不必担心保留周期。

大概,
self
拥有/维护对
\u importContext
的强引用,
\u importContext
可能复制传递到其中的块,并对其具有强引用,并且该块可能会保留
self
,因此它肯定具有保留周期的可能性。我不觉得我能很好地把握什么时候会发生保留循环,这是一个问题,但我确实知道(1)叮当声有时会提醒我它们,(2)很容易对self进行弱引用,并在块内使用它,没有任何负面影响(至少,在您的用例中没有,我也没有看到过).可能重复您的说法是对的,self强烈引用了_importContext。编译器不会在此处警告保留周期,仪器也不会显示周期。我只是想澄清一下,在这种情况下,可能实际上没有一个循环,虽然自我被捕获在块中…感谢澄清。我开始了解这是如何实际工作的。非常感谢。