Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

grandM

macrumors 68000
Original poster
Oct 14, 2013
1,508
298
So guys

I was fooling around with Lazy Instantiation in Swift. Everything works using following code:

Code:
lazy var appDelegate: AppDelegate = (UIApplication.sharedApplication().delegate) as! AppDelegate
lazy var managedObjectContext: NSManagedObjectContext = {
        let appDelegate = (UIApplication.sharedApplication().delegate) as! AppDelegate
        return appDelegate.managedObjectContext
    }()

Both variables were defined as Stored Variable Properties. However when I try to use the lazyily instantiated Stored Variable Property in the initialization of the second Stored Variable Property (hence deleting let appDelegate = (UIApplication.sharedApplication().delegate) as! AppDelegate in the lazy var managedObjectContext closure) I'm getting an error. This error states: instance member 'appDelegate' cannot be used on type ViewController.

Can somebody explain me what I'm doing wrong? Thanks!
 

AxoNeuron

macrumors 65816
Apr 22, 2012
1,251
855
The Left Coast
Do this:

Code:
lazy var appDelegate: AppDelegate = (UIApplication.sharedApplication().delegate) as! AppDelegate
var managedObjectContext: NSManagedObjectContext {
    get {
        return appDelegate.managedObjectContext;
    }
}

The appDelegate variable is already using lazy instantiation. The object context is just a property of it. The only place you would use lazy instantiation of the "managedObjectContext" would be in the AppDelegate file, which is unnecessary since Apple has already given good code for this.
 
  • Like
Reactions: grandM

grandM

macrumors 68000
Original poster
Oct 14, 2013
1,508
298
Do this:

Code:
lazy var appDelegate: AppDelegate = (UIApplication.sharedApplication().delegate) as! AppDelegate
var managedObjectContext: NSManagedObjectContext {
    get {
        return appDelegate.managedObjectContext;
    }
}

The appDelegate variable is already using lazy instantiation. The object context is just a property of it. The only place you would use lazy instantiation of the "managedObjectContext" would be in the AppDelegate file, which is unnecessary since Apple has already given good code for this.
Thanks
I presume I couldn't write
Code:
 var managedObjectContext = appDelegate.managedObjectContext
because the appDelegate was lazy instantiated?
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.