Should IBOutlets be ivars or properties?

余生颓废 提交于 2019-12-03 07:50:48

As a rule of thumb, I usually create accessors for IBOutlets.

In ARC or non-ARC projects I usually do the following:

//.h (ARC)
@property (nonatomic, weak) IBOutlet UILabel* myLabel;

//.h (non-ARC)
@property (nonatomic, retain) IBOutlet UILabel* myLabel;

//.m
@synthesize myLabel;

In this manner you can let the compiler to create an instance variable for you. But you can also declare your instance variable and tell the compiler to use that.

Then you can use that accessors/instance variable wherever you want.

The Apple Memory Management guide says that you have to avoid accessors methods in init or dealloc methods when you have non-ARC projects. So, for example:

// (non-ARC)
- (void)dealloc
{
   [myLabel release]; myLabel = nil; // I'm using the instance variable here!
   [super dealloc];       
}

This is very important in non-ARC projects. The reason is that, if there is no accessor, KVC will assign the nib object to the instance variable and will put a retain on it. If you forget to release it, you could have a memory leak. Using an accessor force you to release that object at the end.

I strongly suggest to read friday-qa-2012-04-13-nib-memory-management by Mike Ash. It's a very cool article on nib and memory management.

Hope it helps.

Here's my understanding

Use properties for variables that will be accessed by other classes, either read from (getters) or written to (setters). Both setters and getters are synthesized for properties.

Use ivars for variables that will be used internally by the owning class only, that is, other classes will not set or get their values.

Sure you can use properties in lieu of ivars, but they incur the function-call overhead whenever they're accessed. So if you have an internal variable that is accessed by your class a LOT, the function calls will affect the real-time performance, and this can be avoided by declaring them as ivars.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!