ios - 为什么不直接使用属性创建对象?

标签 ios objective-c

我正在研究UIPopover,在其中一个示例中,我发现Popover对象是
创建,但随后将对象分配给Viewcontroller的属性。

UIPopoverController* aPopover = [[UIPopoverController alloc] initWithContentViewController:content];
self.popoverController = aPopover;

这种分配的优点是什么?不直接将对象分配给属性的任何原因是什么?

最佳答案

其中没有“功绩”。说

self.popoverController = 
    [[UIPopoverController alloc]  initWithContentViewController:content];

绝对是等效的。

另一方面,如示例所示,使用临时变量(aPopover)并没有错。它只是一个名字(一个指针);不会浪费大量的空间或时间。而且,避免重复重复self.popoverController(设置或获取其值),因为这是一个方法调用-您正在传递setter方法或getter方法(它们可能是合成的,可能会有副作用,并且确实实际上需要一些额外的时间)。因此,例如,当需要完成许多配置时,最好按照您的示例所示进行配置:
UIPopoverController* aPopover = 
    [[UIPopoverController alloc]  initWithContentViewController:content];
// lots of configuration here, using the local automatic variable aPopover...
// ...and then, only when it is all done, call the setter:
self.popoverController = aPopover;

关于ios - 为什么不直接使用属性创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22285897/

相关文章:

iphone - 向上滑动UIView

android - 在 flutter 中,底部重载了 248 像素

ios - 线程安全和 "Collection was mutated while being enumerated"

objective-c - 如何使用大型核心数据集实现更快的搜索

ios - Objective-C 委托(delegate)声明

iphone - 在 iOS(某些版本)中切换声音音量时不一致的 OpenAL 爆音伪像

iphone - 在iphone sdk中将文件夹从资源复制到文档

ios - 如何缩小iphone 7中相机拍摄的照片的大小

ios - 在 viewDidLoad 方法之前填充的 Tableview 单元格

javascript - 一种在 iOS (iPhone, iPad) 上跳过崩溃的方法