什么是unsafe_unretained属性的用法?

我知道unsafe_unretained的定义。

所以我不希望任何人写出它的定义。

我想知道它用于例子,以及它如何与内存pipe理

仅在ARC中存在unsafe_unretained 。 它的工作原理类似于MRC中的assign 。 这些属性不会被保留。 通常情况下,您不会为代表使用这些属性,因为他们不需要拥有这些属性的所有者。

weak属性就像unsafe_unretained只是他们的工作更聪明一点。 当分配给该属性的对象被释放时,弱引用自动变为nil以避免在向该对象(其内存地址)发送消息时发生崩溃。 Unsafe_unretained属性不这样做。 它们将一直保持分配给它的内存地址(除非您手动更改它),而不pipe与该地址关联的对象。 弱引用可以防止在这种情况下崩溃,但结果仍然不会如预期的那样。 如果你的代码写得很好,组织起来就不会发生。

那么为什么你会使用unsafe_unretained而不是weak呢? 弱引用仅在iOS 5和更高版本上可用,所以如果您要构build一个针对iOS 4的ARC应用程序,则需要使用unsafe_unretained属性。 再次,发送消息到发布的属性是不是你想要在任何代码中有任何东西,所以如果你的代码组织的很好,那么你不应该有任何问题。

在之前的ARC中,可以指定委托或其他引用到父属性作为assign以防止保留周期。 随着ARC和较新的编译器的介绍,你会改为使用unsafe_unretained

因此,只要您不需要拥有该引用,并且您不需要或不想使用新的weak引用types(在释放时将该引用设为无效),就可以使用它。

试试这个: 理解ARC下的内存pipe理

这是unsafe_unretained的具体用例。 说两个等级互相参照,一个方向强,另一个方向弱。 在第一堂课的dealloc期间,第二堂课对它的弱点已经是零,阻碍了正确的清理工作。 用unsafe_unretained引用replace弱引用将解决此问题。 请参阅下面的代码示例:

 @class Foo; @interface Bar: NSObject //Replacing weak with unsafe_unretained prevents this property from becoming nil during Foo.dealloc @property (nonatomic, weak) Foo *foo; - (id)initWithFoo:(Foo *)foo; @end @interface Foo : NSObject @property (nonatomic, strong) Bar *bar; - (void)startObserving; - (void)endObserving; @end @implementation Bar - (id)initWithFoo:(Foo *)foo { if ((self = [super init])) { self.foo = foo; //Start observing [self.foo startObserving]; } return self; } - (void)dealloc { //Since foo is a weak property, self.foo may actually be nil at this point! See dealloc of class Foo. [self.foo endObserving]; } @end @implementation Foo - (id)init { if ((self = [super init])) { self.bar = [[Bar alloc] initWithFoo:self]; } return self; } - (void)dealloc { //This will trigger the deallocation of bar. However, at this point all weak references to self will return nil already! self.bar = nil; //endObserving is never called, because Bar.foo reference was already nil. } - (void)startObserving { NSLog(@"Start observing"); } - (void)endObserving { NSLog(@"End observing"); } @end