• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ios - 在 init 中返回 nil 会导致内存泄漏吗?

[复制链接]
菜鸟教程小白 发表于 2022-12-13 10:35:26 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

init中ARC下返回nil会导致内存泄漏,当[super init]已经被调用,然后返回nil?这是合法的用法吗?

- (id)init {
   self = [super init];
   if (self) {

       ...
       return nil;
       ...

   }
   return self;
}



Best Answer-推荐答案


首先:对于引用 ARC 的 Q 从未阅读过 Apple 的文档,而是 clang 的。

Apple 的文档只是隐藏(隐藏?)-init 的执行,并且有这样的错误示例:

id ref = [[Class alloc] init]

你会发现像“+alloc 转移所有权”这样的语句。这至少具有误导性,因为 -init 的返回值而不是 +alloc 的返回值被存储。

到目前为止,clang 的文档更好、更精确。基本上他们说,+alloc 是所有权转移 -init 是所有权消耗和所有权转移。

http://clang.llvm.org/docs/AutomaticReferenceCounting.html#semantics-of-init

Methods in the init family implicitly consume their self parameter and return a retained object.

那么让我们看一下通常的代码:

id ref = [Class alloc]; 
// ref is strong: RC is +1;
id ref = [ref init];    
  // Three things happen her:
  // 1. -init is executed
  // 2. The new value is stored
  // 3. The old value of ref is lost

  // 1. -init is executed
  // self is (silently) passed to the receiver
  - (id)init           
  {
    // Since self is strong (+1), RC is +2 now
    // Since -init is ownership consuming (-1), RC is +1 now
    …
    return self;
    // Since -init is ownership transferring (+1), RC is +2 now
  }

  // 2. The new value is stored
  // The value comes from an ownership transfer method, so the assignment to strong ref is neutral (0), RC is still +2

  // 3. The old value is lost (-1), RC is +1

结果是该对象的 RC 为 +1,并且您在该代码区域中有一个对它的强引用。一切都很好。 (当然有很大的优化潜力,因为在大多数情况下 selfref 都没有改变,但让我们保持正常的轨道。)

让我们在 -init 中更改 self:

id ref = [Class alloc]; // Ownership transfer. RC is +1;
id ref = [ref init];    
  // Three things happen her:
  // 1. -init is executed
  // 2. The new value is stored
  // 3. The old value of ref is lost

  // 1. -init is executed
  //     self is (silently) passed to the receiver
  - (id)init           
  {
    // Since self is strong (+1), RC is +2 now
    // Since -init is ownership consuming (-1), RC is +1 now

    // Let's return nil as in your example
    return nil;
    // Because nil is returned, virtually the RC of nil is increased. self's RC == +1 is unchanged.
  }

  // 2. The new value is stored
  // The new value is nil.
  // However the value comes from an ownership transfer method, so the assignment to strong ref is neutral (0), RC is still +1

  // 3. The old value is lost (your old ref and the self while executing -init) (-1), RC is 0
  // The old object is dealloced, if you do not have another ref to it. Nothing leaks.

关于ios - 在 init 中返回 nil 会导致内存泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29603467/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap