【问题标题】:Why should I prefer the unsafe_unretained qualifier over assign for weak referencing properties? [duplicate]为什么我应该更喜欢 unsafe_unretained 限定符而不是为弱引用属性赋值? [复制]
【发布时间】:2023-03-24 15:14:01
【问题描述】:

可能重复:
using ARC, lifetime qualifier assign and unsafe_unretained

两者有什么区别?

@property(unsafe_unretained) MyClass *delegate;
@property(assign) MyClass *delegate;

两者都是非归零弱引用,对吧?那么有什么理由让我写更长更难读的unsafe_unretained而不是assign

注意:我知道有 weak 这是一个归零参考。但它只是 iOS >= 5。

【问题讨论】:

标签: iphone ios memory-management automatic-ref-counting


【解决方案1】:

在属性访问器中,是的,它们是相同的。对于这种情况,assign 属性将映射到 unsafe_unretained。但请考虑手动编写 ivar 而不是使用 ivar 合成。

@interface Foo
{
   Bar *test;
}
@property(assign) Bar *test;
@end

此代码现在在 ARC 下是不正确的,而在 ARC 之前则不是。所有 Obj-C 对象的默认属性是 __strong 向前移动。向前推进的正确方法如下。

@interface Foo
{
   __unsafe_unretained Bar *test;
}
@property(unsafe_unretained) Bar *test;
@end

或使用 ivar 合成只需 @property(unsafe_unretained) Bar *test

所以实际上它只是写同一件事的不同方式,但它表现出不同的意图。

【讨论】:

  • 我可以在 iOS 4 中使用 ivar 合成吗?或者这只是iOS 5?使用 iVar 合成时我还需要注意什么?
  • 所有 iOS 回到 2.0 的版本都支持这个。
猜你喜欢
  • 2010-10-18
  • 2017-12-21
  • 2011-04-01
  • 2017-01-01
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-16
相关资源
最近更新 更多