lazy instantiation in swift

Discussion in 'iOS Programming' started by grandM, Nov 17, 2015.

  1. grandM macrumors 6502a

    grandM

    Joined:
    Oct 14, 2013
    #1
    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!
     
  2. AxoNeuron macrumors 65816

    AxoNeuron

    Joined:
    Apr 22, 2012
    Location:
    The Left Coast
    #2
    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.
     
  3. grandM thread starter macrumors 6502a

    grandM

    Joined:
    Oct 14, 2013
    #3
    Thanks
    I presume I couldn't write
    Code:
     var managedObjectContext = appDelegate.managedObjectContext 
    because the appDelegate was lazy instantiated?
     

Share This Page