IRP_HANDLER
IRP_HANDLER

Reputation: 308

Objective-C Appropriate usage of ivar instead of property for lazy instantiation

So in swift there are "lazy vars" so I wanted to try the same thing in objective-c.

Say I have a class with the following property:

@interface MainWindowController : NSWindowController<NSWindowDelegate>

@property(nonatomic, strong) NSTabViewController *tabViewController;

@end

After reading multiple questions here I noticed that people are always encouraged to access properties via :

self.tabViewController

rather than:

_tabViewController

but if I want to use lazy instantiation for this property I am pretty much compelled to use the backing ivar am I right? Like for the getter:

(NSTabViewController *)tabViewController
{
    if( !_tabViewController )
    {
        _tabViewController = [[NSTabViewController alloc] init];
        // ...
    }
    
    return _tabViewController;
}

if I use self.tabViewController here in the if statement it would recursively call the getter forever.

Is this considered a correct usage of _ivar instead of self.ivar?

Upvotes: 0

Views: 50

Answers (0)

Related Questions