Home > iPhone, Objective-C > Objective-C Pitfall: Synthesized Properties without backing field

Objective-C Pitfall: Synthesized Properties without backing field

This is just a quick and short post about an Objective-C pitfall I have encountered today. When using synthesized properties, you do normally supply a backing field:

@property (nonatomic, readwrite, retain) Message* message = message_;

This will synthesize a getter and setter, that will use message_ as its backing field. Since I found out one can go clever and ommit the backing field, so a simple line like this will work too:

@property (nonatomic, readwrite, retain) Message* message;

However, now we get into a bit of trouble when accessing the property. Contrary to the behavior in Java or C#, you now get something different when accessing 

self.message

 vs.

message

. While the former will use the synthesized getter, the latter will use the synthesized backing field directly. This is a bit unexpected (I thought the backing field would be anonymous). So, my general advice would be to always use backing fields in your synthesized backing fields, so you don’t accidentally forget a “self.”. (This is water on the mills of people that advocate _not_ using the dot syntax for properties).

 

 

Advertisements
Categories: iPhone, Objective-C
  1. Brian Palma
    December 28, 2011 at 23:05

    I didn’t know you were able to declare a backing field in the @property declaration.

    Isn’t this the convention:

    In .h file: @property (nonatomic, readwrite, retain) Message *message;

    In .m file: @synthesize message = message_;

    Then using self.message and [self message] will access the same iVar. No?

    • January 26, 2012 at 22:44

      self.message and [self message] do never access an iVar directly, both of them will invoke the method with the name message on self. Rember that the dot-Notation (x.property) is just syntactic sugar for [x property].
      The “convention” you listed is certainly fine and is what Google recommends in their Objective-C Style Guide. I use this when I do want to explicitly create an iVar.

      The trick I presented in the post does not only synthesize the property, it also synthesizes the iVar. In this case you need to be aware of possible pitfalls.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: