0

I have created a UIViewController in the .h file named myViewController.

Should I refer to it in the .m file with self.myViewController or _myViewController (being autosynthesized with that name).

Is it a personal preference or is there any difference between the two? If so, what is the difference?

Sorry for asking a strange question, but I didn't know how to google this.

Martin Schröder
  • 4,176
  • 7
  • 47
  • 81
Lord Zsolt
  • 6,492
  • 9
  • 46
  • 76

1 Answers1

1

Basics

Using the dot syntax is completely different from using the auto-synthesized underscore-prefixed instance variable!

When you declare a property (let's say name of type NSString *) in a class Person you get implicitly this:

@interface Person : NSObject
// @property (copy) NSString *name;
// Results in
- (NSString *)name;
- (void)setName:(NSString *)name;
@end

Plus the implementation of these methods which do nothing different than setting _name. _name is an private instance variable which is created when a property is synthesized (obviously if the property has the name viewController the name of the ivar is _viewController).

So using the “dot syntax” calls one of the two generated methods, depending on whether you assign a value or read a value.

If you want you can give the underlying ivar a different name by explicitly synthesizing the property and assigning a new name.

@implementation Person
@synthesize name = nameOfThisPerson_ivar;
...
@end

Now you won't see _name any more in the code completion but nameOfThisPerson_ivar.

Or you can implement your own name and setName: methods (or just one) but then you have to assign the value yourself (in the setter) and you have to copy it yourself, if the property's attribute is copy; if your property should be atomic, this has to be implemented by you and so on.

So what to use?

Prior to ARC you should always use the dot notation which actually calls one of the two generated methods because there the retain/release memory management was implemented for you. And I think you should still use properties because then you can e.g.

  • easily implement Lazy initialization
  • you can easily have thread safety (just by not specifying nonatomic in your properties' attributes)
  • and a lot of other stuff …

Edit

As Catfish_Man pointed out in the comments atomic properties do not guarantee thread safety

JDS
  • 1,173
  • 12
  • 26
  • 1
    Note that atomic properties do not guarantee thread safety, and in fact are only moderately useful for implementing it. They do guarantee two useful attributes: 1) *some* valid value will always be read, you won't get a partial value, and 2) the read value will be retained and put in the current thread's autorelease pool, so if another thread releases it, it won't unexpectedly disappear. No synchronization or serialization beyond that is provided; you'll have to use locks, queues, etc... for that. – Catfish_Man Jul 09 '13 at 18:26