Semantic Conventions: Underscore before instance variables?


#1

I’ve noticed that some other iOS dev bloggers tend to use this convention:

As I understand, this is to give a quick visual queue that you’re dealing with an instance variable vs a method or something like that. I’m curious about the challenges and benefits of choosing this convention vs what’s demonstrated in the book. Question for the authors (or other seasoned devs): Do you find that situations don’t come around often enough to justify the extra typing? Or is it just something that you’ve gotten used to as you’ve become more experienced?

If this question is asked elsewhere on the forums, my apologies. I couldn’t find it.


#2

Naming instance variables this way helps prevent compiler warnings caused by ambiguous references.

For example:

@implementation Foo

@synthesize iVar; // This will also define an instance variable named iVar

- (void) workWith:(IVarType)iVar
{
   iVar = ... iVar ...;  // which one did you have in mind?
}
end

@implementation Foo

@synthesize iVar = _iVar; // Here instance variable is explicitly named _iVar

- (void) workWith:(IVarType)iVar
{
   _iVar = ... iVar ... ; // no ambiguity here
}
end

#3

That definitely makes sense. I’m curious as to why the book is written without dis-ambiguizing the ivars. I’ve tried to make sure that as I went through the book I ‘fixed’ it to include the underscores.


#4

Hi, I’m approaching for the first time the objc + iOS programming, and I’ve found useful read the Coding Guidelines for Cocoa of the Apple’s developer library, and good books also try to follow those specifications.

This is the base url: developer.apple.com/library/mac … lines.html

and this is the specific guide regarding the properties and instance variables: developer.apple.com/library/mac … Types.html

In short also Apple suggest the use of the underscore prefix for the synthesize instance variables, to better understand on which reference you’re working on. This has NOT to be confused with the declaring of a private method where Apple discourage the use of the underscore as a method prefix (Apple reserves this convention), because you can fall in an unwanted overload of a cocoa private method, while you’re subclassing a cocoa class.

Cheers!
Michael.


#5

@ashtonbt1
We don’t use ivar decorations in the book to avoid this discussion early on in the course. The book attracts both experienced programmers from other platforms, and people brand new to programming. Other than ambiguous references it shouldn’t matter for the exercises in the book.

Mark Dalrymple wrote a great article for our blog about this exact topic. Check it out:
weblog.bignerdranch.com/463-a-mo … corations/