gpt4 book ai didi

Objective-C - 弱属性 - getter autoreleases(自动引用计数)

转载 作者:搜寻专家 更新时间:2023-10-30 19:42:13 26 4
gpt4 key购买 nike

我对 ARC 中的 weak 属性有疑问(自动引用计数)

我的理解(如有错误请指正):

weak 属性的行为类似于 assign 属性,不同之处在于当该属性指向的实例被销毁时,ivar 将指向 nil。

问题:

  1. 我只是觉得weak属性的getter retains和autoreleases。它不应该像 assign 属性的 getter 一样,其中 getter 不保留和自动释放吗?(请引用程序)

程序:

我在下面给出了程序的实际输出和我的预期输出。

注意 - 当我将属性从 weak 更改为 assign 时,我的预期输出得到满足

#import<Foundation/Foundation.h>

@interface A : NSObject
- (void) dealloc;
@end

@implementation A
- (void) dealloc
{
printf("\tinstance of A deallocated = %p\n", self);
}
@end

@interface B : NSObject
@property (weak) A* xa1;
- (void) dealloc;
@end

@implementation B
@synthesize xa1;
- (void) dealloc
{
printf("\tinstance of B deallocated = %p\n", self);
}
@end


int main()
{
B* b1 = [[B alloc] init];

@autoreleasepool //autoreleasepool 1
{
{ //block 1
A* a1 = [[A alloc] init];
printf("\ta1 = %p\n", a1);

b1.xa1 = a1;

A* a3 = b1.xa1;

printf("--- end of block 1\n");
} //at this point i expected instance pointed by a1 to be destroyed

printf("--- end of autoreleasepool 1\n");
}

printf("---- end of main\n");

return(0);
}

实际输出:

    a1 = 0x10d713f50
--- end of block 1
--- end of autoreleasepool 1
instance of A deallocated = 0x10d713f50
---- end of main
instance of B deallocated = 0x10d713d30

我的预期输出:

    a1 = 0x10d713f50
--- end of block 1
instance of A deallocated = 0x10d713f50
--- end of autoreleasepool 1
---- end of main
instance of B deallocated = 0x10d713d30

谢谢

最佳答案

在属性上提供 weak 假定 __weak 对 ivar 的所有权,即它只是 @synthesize 的指令。

根据 http://clang.llvm.org/docs/AutomaticReferenceCounting.html §4.2,读取__weak变量需要保留对象(当然是之后释放):

Reading occurs when performing a lvalue-to-rvalue conversion on an object lvalue.

  • For __weak objects, the current pointee is retained and then released at the end of the current full-expression. This must execute atomically with respect to assignments and to the final release of the pointee.
  • For all other objects, the lvalue is loaded with primitive semantics.

它没有说明原因,但想一想如果您从 __weak 变量获得的对象在您开始使用它之前就死了会发生什么。弱指针的目的是确保您拥有 nil 或具有众所周知生命周期的有效对象,这就是为什么读取它的值意味着保留指针(然后属性的 getter 返回它自动释放)。

这不是 Obj-C 独有的,它是所有弱指针实现(包括引用计数和垃圾收集)的常用习惯用法。弱指针不能直接给出指针值,它们必须创建指向“持有”对象的强指针,以确保它不会在调用者开始使用它之前就死掉。在 Obj-C 中,它是 retain-autorelease;在 C++ 中,weak_ptr 首先创建 shared_ptr,在垃圾收集环境中,返回一个强引用并默默地延长对象的生命周期。

关于Objective-C - 弱属性 - getter autoreleases(自动引用计数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8148551/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com