(puttin’ the grumpy hat on, full Crusty mode)
Don’t use instance variables
Before properties, Objective-C code was usually like this:
1 2 3
and then followed by explicit getter and setter methods in implementation that read or set this
_internalVar. If you are still using this – stop. When I see code written like this, I dismiss it as obsolete and move on to something else.
@property. Always and ever.
Use private header for most properties
This is your public header, your public API, which goes in the
1 2 3
And this is your private header, your storage for the internal properties and this one goes into your
1 2 3
Always use properties with dot syntax
When you need to reference the property, always use
self.internalVar. Don’t use
[self someVar] nor
[self setSomeVar:@""] as that hurts readability of the code (unless you are working in watchOS).
Never, ever use
_internalVar anywhere in your code except
initXX methods. You can use
self.someVar even in there since
self already exists – you did write
self = [super init] as the very first line, right? – but it seems wrong to me to reference the object while it’s still being initialized.
Additionally, use dot syntax for any existing methods that sound-like and behave like properties. Examples are
[someArray count] or
[someString length] – Apple keeps them as methods because they were created several decades ago. Consistency matters in APIs.
If they were introduced today, they would certainly be properties: so please:
someArray.count. As a general rule: any getter method without parameters that does not have corresponding setter is a candidate to be treated as property.
The beauty of the way
@property internally works is that
someString.length is possible to do. So make some good use of that.
Never use dot syntax with actual methods
The ugliness of the way
@property internally works is that it makes this possible too:
This is horrible. I hate this so much that I would abandon/avoid using a component written like this no matter how useful it is.
Method is a method. Respect the language idioms or go use something else if you hate the square brackets so much.