iosdev

Masterclass: Objective-C mandatory rules

puttin’ the grumpy hat on, full Crusty mode

Don’t use instance variables

Before properties, Objective-C code was usually like this:

@interface XXSomething {
NSString *_internalVar;
}

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.

Use @property. Always and ever.

Use private header for most properties

This is your public header, your public API, which goes in the XXSomething.h file:

@interface XXSomething
@property (nonatomic) NSString *someVar;
@end

And this is your private header, your storage for the internal properties and this one goes into your XXSomething.m file:

@interface XXSomething ()
@property NSString *internalVar;
@end

Always use properties with dot syntax

When you need to reference the property, always use self.someVar or 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 _someVar or _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:

NSArray *arr = NSArray.new;
RTDataManager.fetchNewdata;

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.