我们在ARC中创建对象的这两种方式有什么区别吗?

时间:2015-07-06 16:36:08

标签: ios objective-c automatic-ref-counting

我想知道实际上是否有任何区别:

UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.deleteButton = deleteButton;

self.deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];

使用ARC时?

我看到很多人在第一种情况下写了很多代码,但我相信第二种方式更简洁,更清晰简洁。

2 个答案:

答案 0 :(得分:1)

  

实际上

之间有什么区别

是的,但是,在编译器优化下,生成的二进制文件将是相同的。

UIButton *deleteButton,即UIButton __strong *deleteButton拥有该对象的所有权。

该对象已在当前自动释放池中注册,因为buttonWithType:类方法不以“alloc”,“new”,“copy”或“mutableCopy”开头。

因此,

UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];

/*
 * The current Autorelease Pool has ownership of the object. retainCount=1
 * __strong deleteButton has ownership of the object as well. retainCount=2
 */

self.deleteButton = deleteButton;

/*
 * If self.deleteButton is strong property, it has ownership of the object too. retainCount=3
 * If self.deleteButton is weak property, it doesn't have ownership of the object. retainCount=2
 */

答案 1 :(得分:0)

不是ARC专家或此处的任何内容,但我相信代码是完全相同的。分配给指针时,您将指定指针指向的内存地址。你在顶部和底部之间做的唯一事情就是将内存地址保存在本地指针中,然后再将其分配给self.deleteButton。