ios - 自定义代理delegate为什么只能设置成unsafe_unretained,不能是assign;unsafe_unretained属性为什么容易导致指针丢失,丢失后调用就会SIGBUS,如何避免
伊谢尔伦
伊谢尔伦 2017-04-17 10:59:41
0
4
397

工程启用ARC后,delegate不能设置成assign属性了,只能是unsafe_unretained么

//.h
id __unsafe_unretained _delegate;
@property(nonatomic,unsafe_unretained) id <EGORefreshTableHeaderDelegate> delegate;

//.m
@synthesize delegate=_delegate;

if (!_delegate) {
    return;
}

unsafe_unretained的指针应该如何避免对象指向丢失,一旦丢失,即使是上面的if判断调用都会crash,如何处理呢

求教!!!

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(4)
阿神

正确的写法是
__unsafe_unretained id<EGORefreshTableHeaderDelegate> _delegate;
@property(nonatomic,assign) id <EGORefreshTableHeaderDelegate> delegate;
crash和此处无关,是你别的地方已经释放了此对象。

如果此处改为强引用,则不可避免的造成retain cycle从而内存泄露,是万万不能的。你要做的是检查为何释放后还会被回调。

巴扎黑

开启ARC后,如果部署iOS版本是5.0以上,请使用weak,5.0以下的才用unsafe_unretained,楼上说的设置成strong是不对的

大家讲道理

请看官方的说明:

~~Note: In addition, in OS X v10.7, you cannot create weak references to~~
~~instances of NSFontManager, NSFontPanel, NSImage, NSTableCellView,~~
~~NSViewController, NSWindow, and NSWindowController. In addition, in OS~~
~~X v10.7 no classes in the AV Foundation framework support weak~~
~~references.~~
~~For declared properties, you should use assign instead of weak; for~~
~~variables you should use __unsafe_unretained instead of __weak.~~
ARC is supported in Xcode 4.2 for OS X v10.6 and v10.7 (64-bit applications) and for iOS 4 and iOS 5. Weak references are not supported in OS X v10.6 and iOS 4.

~~考虑到delegate的类型不确定性与非拥有性,毫无疑问:~~

  • ~~weak是不能使用的~~
  • ~~strong是绝对错误的~~
  • ~~assign是没有问题的~~
  • ~~unsafe_unretained是表意清晰的~~

由于delegate的非拥有性,在ARC下应该首选weak,因为它可以防止野指针问题,更加安全。
但如果在iOS4下,由于还未支持weak,就只能退而求其次,使用unsafe_unretained了。

大家讲道理

开启ARC后,不需要设置成unsafe_unretained,设置成strong即可

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!