比如:
ClassA* objA = [[[ClassA alloc] init] autorelease];
objA.myBlock = ^{
[self doSomething];
};
self.objA = objA;
就会导致self无法释放。。
只能 __weak MyClass* weakSelf = self;
然后objA.myBlock中: [weakSelf doSomething];
这种问题大家有什么经验避免吗??这个很难发现呀。
没错,这个很难发现的。。。。只能遵守规则。而且有些地方该用回调的还是用回调的好。
另外,开了ARC之后,出现retain circle的地方会给出warning的。
解决方案就是:传递NSObject的时候一定要在心里过一遍谁拥有谁,千万别以为开了ARC就不用内存管理了,引用计数和自动GC是有本质区别的。
另一个解决方案就是学C++,所谓不会C++的Obj-C程序员不是一个好C程序员
10楼 @terryso 是的。其实关于block内存管理 官方文档里有提到,可能大家都没注意到。
When a block is copied, it creates strong references to object variables used within the block. If you use a block within the implementation of a method:
If you access an instance variable by reference, a strong reference is made to self;
If you access an instance variable by value, a strong reference is made to the variable.
The following examples illustrate the two different situations:
dispatch_async(queue, ^{
// instanceVariable is used by reference, a strong reference is made to self
doSomethingWithObject(instanceVariable);});
id localVariable = instanceVariable;
dispatch_async(queue, ^{ /* localVariable is used by value, a strong reference is made to localVariable (and not to self).
10楼 @terryso 是的。其实关于block内存管理 官方文档里有提到,可能大家都没注意到。
When a block is copied, it creates strong references to object variables used within the block. If you use a block within the implementation of a method:
If you access an instance variable by reference, a strong reference is made to self;
If you access an instance variable by value, a strong reference is made to the variable.
The following examples illustrate the two different situations:
dispatch_async(queue, ^{
// instanceVariable is used by reference, a strong reference is made to self
doSomethingWithObject});
dispatch_async(queue, ^{
/*
localVariable is used by value, a strong reference is made to localVariable
(and not to self).
*/
doSomethingWithObject(localVariable); });
block本身是一个对象。你可以把block捕获到的对象当做这个block的@property(strong)来处理(强引用)。另外,如果block捕获了当前对象的实例变量,那这个block也会对当前对象有强引用。稍微注意一下就能避开circle了,xcode也会帮你做一部分检查的。