For me the past as Objective-C developer was simple. Every field a class needed to be public was a property and every private field was an instance variable without getter or setter. But much more often I see people using a private interface inside the implementation file to declare private properties. And I have been told that is the way to do things now.
While this works fine it is hard for me to see the advantages. As long I do not need some logic in the getter or setter I would go on still using instance variables for everything not public. I have to admit using a property and then using keyword self make the code a bit more readable. You can see if a property belongs to the class or if it is just a local variable inside a method but that can not be the only reason.
Why or why not use private properties?
I use properties for the interface part - where the object interfaces with other objects and instance variables are stuff that you need inside your class - nobody but you is supposed to see and manipulate those.
By making the variable a private data member, you can more easily ensure that the value is never negative. On the other hand, if the variable is public, another class could change it to a negative value which can cause other parts of the code to crash.
The Objective-C declared properties feature provides a simple way to declare and implement an object's accessor methods.
There are a couple of reasons to use (private) properties over ivars.
First, if you do not need a private property, do not use a property: unless you want to get some specific behavior from the compiler declaratively, such as forcing NSString
copying on assignment, there is no benefit to using properties.
Moreover, you do not necessarily need to use self
to access these properties: when a property is synthesized for you, automatically or with a @synthesize
keyword, you get a variable that "backs" the property. Assigning that variable is a perfectly legal way of accessing the property, for example, when you want to present it as read-only.
However, it an advantage to making these variables private, i.e. to declaring them in a class extension, like this:
@interface MyClass() { // <<== Note the () -- it's a class extension
SomeOtherClass *privateIvar;
}
If you declare a variable in a class extension (which goes in .m file instead of a header) you would be able to hide the header for "SomeOtherClass"
, which is of little importance when you develop a single app, but becomes very useful when you start developing with your own class libraries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With