I see it recommended all over the place when coding for iOS that properties should be used for accessing instance variables because of the benefits this lends to memory management, among other things.

This advice doesn't sit terribly well with me. I find that using properties instead of plain old ivars just takes too much code and I don't really see the benefits if you're comfortable with memory management. Is it really that important? What's your approach to managing instance variables?

推荐答案

It's not really necessary to declare properties for all ivars. A few points come to mind:

  • If an ivar is only going to be assigned to once during the lifetime of the object, you don't really gain anything by declaring a property. Just retain/copy/assign during init and then release as necessary during dealloc.
  • If an ivar is going to be changed frequently, declaring a property and always using the accessors will make it easier to avoid memory management errors.
  • You can declare properties in a class extension in the .m file rather than the .h file if the properties and ivars are meant to be private.
  • When targeting iOS 4.0+, you don't need to declare ivars at all in your header if you define a property and synthesize accessors.

So I generally use properties, but for things like a NSMutableArray that an object allocates during init and uses to hold a bunch of whatevers, I'll use a plain old ivar since I'll never be reassigning the ivar.

Objective-c相关问答推荐

UITableViewCell:如何防止蓝色 Select ​​背景不带 isSelected 属性?

如何在没有 Interface Builder 的情况下创建 Cocoa 接口?

UIApplication.sharedApplication.delegate.window 和 UIApplication.sharedApplication.keyWindow 有什么区别?

在@implementation 而不是@interface 定义的类变量?

iOS 指定初始化器:使用 NS_DESIGNATED_INITIALIZER

当我从导航控制器推送时如何隐藏导航栏?

Objective-C (cocoa) 等价于python的endswith/beginswith

iOS7过度导航栏按钮填充

从我在 iPhone 上的应用程序调用官方 *Settings* 应用程序

关于如何将项目从 UITableView 拖放到 UITableView 的教程

在 iPhone 上测量人体胀气( Human-Flatulence)传播波包

接口类型不能静态分配?

使用情节提要的条件转场

当用户返回视图控制器时如何取消 Select uitableview 单元格

UITabBar 未在 ios 7 中显示所选项目图像

如何确定 UICollectionView flowLayout 中单元格之间的间距

AdMob 因 [GADObjectPrivate changeState:] 崩溃:无法识别的 Select 器

ARC时代的财产与ivar

Instruments Allocations 跟踪用户定义类的对象的分配和解除分配

有没有办法在用户已经在 iOS 上拒绝相机访问权限后向他们询问?