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。编译器不会在此处警告保留周期,仪器也不会显示周期。我只是想澄清一下,在这种情况下,可能实际上没有一个循环,虽然自我被捕获在块中…感谢澄清。我开始了解这是如何实际工作的。非常感谢。