self.dictionary[blah] = 带有使用自身的块的对象:在 ARC 中创建引用计数循环?
self.dictionary[blah] = object with block that uses self: creates a ref-count loop in ARC?
我有一个 class 使用 ARC,它有一个成员 属性,它是一个可变字典。然后我为该字典中的一个键设置一个值。该值是一个对象,其中包含一个引用该对象自身的块。
- (void)doSomethingLaterWithVar:(id)var forSlot:(id)slot {
self.doThingsLater[slot] = [DoLaterThingie doAfterNSecs: 5 block:
^(DoLaterThingie *dlt) {
[self.log addObject:@"Did Thingie!!!"]
}
];
}
我是否创建了引用计数循环?这是一个有点人为的例子,但基本上捕捉到了我正在做的事情。我已经设法将我的大脑集中在简单的案例上,但不确定这些循环可以进行多深。
你必须创建一个弱自我来防止保留循环。
- (void)doSomethingLaterWithVar:(id)var forSlot:(id)slot {
__weak id weakSelf = self;
self.doThingsLater[slot] = [DoLaterThingie doAfterNSecs: 5 block:
^(DoLaterThingie *dlt) {
[weakSelf.log addObject:@"Did Thingie!!!"]
}
];
}
在一个块中,如果你不使用 weak self,self
将保留该块并且该块将保留 self
并且都不会被释放。
我有一个 class 使用 ARC,它有一个成员 属性,它是一个可变字典。然后我为该字典中的一个键设置一个值。该值是一个对象,其中包含一个引用该对象自身的块。
- (void)doSomethingLaterWithVar:(id)var forSlot:(id)slot {
self.doThingsLater[slot] = [DoLaterThingie doAfterNSecs: 5 block:
^(DoLaterThingie *dlt) {
[self.log addObject:@"Did Thingie!!!"]
}
];
}
我是否创建了引用计数循环?这是一个有点人为的例子,但基本上捕捉到了我正在做的事情。我已经设法将我的大脑集中在简单的案例上,但不确定这些循环可以进行多深。
你必须创建一个弱自我来防止保留循环。
- (void)doSomethingLaterWithVar:(id)var forSlot:(id)slot {
__weak id weakSelf = self;
self.doThingsLater[slot] = [DoLaterThingie doAfterNSecs: 5 block:
^(DoLaterThingie *dlt) {
[weakSelf.log addObject:@"Did Thingie!!!"]
}
];
}
在一个块中,如果你不使用 weak self,self
将保留该块并且该块将保留 self
并且都不会被释放。