Stylistic choices - initializers; ivars vs properties


#1

I have a couple of general questions about the book’s style of coding in Obj-C.

With initializers, I have commonly seen the following (or similar) in code examples elsewhere:

(id)init { if (self = [super init]) { // do stuff here } return self; }

In the book you seem to do the following:

(id)init { [super init]; // do stuff here return self; }

I prefer your approach. It seems cleaner, and I think if [super init] fails, there’s a bigger problem that my method. Another thing I dislike in the former style is the assignment to self; it seems wrong to me to change the value of self.

Can you clarify why you chose your style for init?

Another question is about using ivars or properties. When is it okay to have an ivar only as an ivar, and when is it best to have a property? In other words, what is the best practice accessors? I’ve seen code that uses no properties (except for IB) and code that has every ivar declared as a property. I find myself not specifying properties for values that I know will only be used within the class. (In comparison, I’m familiar with Java and C++ access rules, although it’s been a while since I’ve used either.)

On a related note, I noticed a couple places in the book where you use dot-notation. It’s the same kind of places I find it easier to use dot notation as well: accessing things like center.x and bounds.size.width.


#2

We use our form of initializers because yes, there is something bigger going on if an initializer fails. The objects in the SDK will not fail in initializing. It’s just more typing for no real purpose using the check.

You use properties when you want other objects to be able to access the ivars of an object. That’s the only reason to use them.

The .'s in center.x or bounds.size.width are not dot syntax. This is from the C language. They are member access for structures - they are a memory offset and a direct read/write. This is why dot syntax is stupid - the . operator is already used in the language for something that, while similar, is very different.