Question

(Just to let you now, I'm learning to develop for iPhone with a book I got called Beginning iPhone 3 Development: Exploring the SDK, and I do not use Interface builder) Is there ever a reason to use the getter in the same class, when a private member is visible? Like in Foo.h, having

NSObject *myObj;
...
@property (nonatomic, retain)NSObject *myObj;

and then in Foo.m, accessing the member myObj using self.myObj (or [self myObj]) ? Because in my book, Here is what it tells you to write in one of the apps (its checking if a UIViewController member's view is in the superview) :

if(self.yellowViewController.view.superview == nil) {

(notice the self.yellowViewController...) Is there actually a reason for this? If there isn't one idea I have is maybe because the member blueViewController is of class BlueViewController, so I think if there is no reason it may be to not cause confusion. So is there anytime where using the getter in the same class is needed?

Thanks!!

Was it helpful?

Solution

Yes, accessing your ivars through a getter than directly is a good thing to do.

As an example: One of the normal design patters in Cocoa (especially on the phone, where resources are very limited) is called lazy loading.

Summed up, it means don't load a resource until you need it.

Ideally, you would want to place code in your getter that would check to see if the resource being requested is loaded, and if not, load it. Accessing the ivar directly would just return nil. The alternative would be to initialize all of the ivars when your parent class is init'ed, thereby potentially wasting resources to store data that may or may not be needed.

This also allows you to potentially place resources that could potentially be retrieved again in your applicationDidReceiveMemoryWarning: methods and dump them when resources got tight, because they will be loaded again on demand when needed.

OTHER TIPS

Lazy loading getter:

- (UIImageView*) getImageView
{
    if (!imageView)
    {
        imageView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"blah.png"]]; // just an example
    }
    return imageView;
}

Depending on how imageView is defined (copy, assign, retain) you will need to modify the actual assignment, but this is what is meant by lazy loading.

A few reasons to use the self.ivar getter syntax instead of directly accessing the instance variable:

  • Lazy-loading properties, as others have mentioned
  • Subclasses may want to override the property and have the superclass respect that
  • If you use atomic properties, the only correct way to access the property is through the getter
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top