ios 中的以下代码片段中 ARC 如何工作?
How does ARC work in the following code snippet in ios?
假设我有一个方法 returns 一个对象指针
-(MyObj *) returnMyObj {
MyObj *obj = [MyObj alloc] init];
return obj;
}
如果我调用这个函数而不像这样分配指针
场景一
[self returnMyObj];
如果我调用这个函数并赋值给这样的指针
场景二
MyObj* obj = [self returnMyObj];
编译器可以在场景 1 中的 returnMyObj 方法调用结束时释放对象,但它不能在场景 1 中做同样的事情 2.How ARC 是否决定它是否在这两种情况下是否需要在方法调用结束时保留创建的对象?
如果稍后在块中未引用 obj
,优化器可能会在语句末尾完全释放方案 2 中的对象。
重点是优化器可以看到指针何时被引用,并可能在最后一次引用完成后立即释放它。 obj
没有精确的生命周期语义,所以它只会延长对象的生命周期直到最后一次 obj
被引用,而不是当 obj
超出范围时。
在场景一中,引用没有赋值给任何变量,所以显然没有后面的引用,可能会被立即释放。也就是说,它可能不会立即释放该对象,因为 returnMyObj
不会将所有权转移给调用者(由于其名称)。因此,在自动释放池耗尽之前,对象可能不会真正被释放。
文档中的 ARC article 是这么说的:
To make sure that instances don’t disappear while they are still needed, ARC tracks how many properties, constants, and variables are currently referring to each class instance. ARC will not deallocate an instance as long as at least one active reference to that instance still exists.
To make this possible, whenever you assign a class instance to a property, constant, or variable, that property, constant, or variable makes a strong reference to the instance. The reference is called a “strong” reference because it keeps a firm hold on that instance, and does not allow it to be deallocated for as long as that strong reference remains.
ARC 通过计算对对象的强引用来决定哪些对象将保留在内存中,哪些将被释放。
在第二种情况下,您正在创建对 MyObj
实例的强引用,并且 ARC 不会在对象正在使用时释放它。在这种情况下,它将在使用该对象的方法完成时被释放。
假设我有一个方法 returns 一个对象指针
-(MyObj *) returnMyObj {
MyObj *obj = [MyObj alloc] init];
return obj;
}
如果我调用这个函数而不像这样分配指针
场景一
[self returnMyObj];
如果我调用这个函数并赋值给这样的指针
场景二
MyObj* obj = [self returnMyObj];
编译器可以在场景 1 中的 returnMyObj 方法调用结束时释放对象,但它不能在场景 1 中做同样的事情 2.How ARC 是否决定它是否在这两种情况下是否需要在方法调用结束时保留创建的对象?
如果稍后在块中未引用 obj
,优化器可能会在语句末尾完全释放方案 2 中的对象。
重点是优化器可以看到指针何时被引用,并可能在最后一次引用完成后立即释放它。 obj
没有精确的生命周期语义,所以它只会延长对象的生命周期直到最后一次 obj
被引用,而不是当 obj
超出范围时。
在场景一中,引用没有赋值给任何变量,所以显然没有后面的引用,可能会被立即释放。也就是说,它可能不会立即释放该对象,因为 returnMyObj
不会将所有权转移给调用者(由于其名称)。因此,在自动释放池耗尽之前,对象可能不会真正被释放。
文档中的 ARC article 是这么说的:
To make sure that instances don’t disappear while they are still needed, ARC tracks how many properties, constants, and variables are currently referring to each class instance. ARC will not deallocate an instance as long as at least one active reference to that instance still exists.
To make this possible, whenever you assign a class instance to a property, constant, or variable, that property, constant, or variable makes a strong reference to the instance. The reference is called a “strong” reference because it keeps a firm hold on that instance, and does not allow it to be deallocated for as long as that strong reference remains.
ARC 通过计算对对象的强引用来决定哪些对象将保留在内存中,哪些将被释放。
在第二种情况下,您正在创建对 MyObj
实例的强引用,并且 ARC 不会在对象正在使用时释放它。在这种情况下,它将在使用该对象的方法完成时被释放。