Must every ivar be a property?

Diego picture Diego · Feb 17, 2011 · Viewed 17.9k times · Source

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?

Answer

Daniel Dickison picture Daniel Dickison · Feb 17, 2011

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.