1

When using Core Data, we obtain the managedObjectContext using our AppDelegate like so:

override func viewDidLoad()
{
    super.viewDidLoad()

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedObjectContext = appDelegate.managedObjectContext
}

Now when I remove these two lines of code from viewDidLoad in an attempt to store them as instance variables on ViewController, I get an error.

The issue is that I cannot use "appDelegate", as it is already an instance variable.

I understand that I can solve this by simply doing:

let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

However, I was curious if it is possible to declare both as instance variables. I'm assuming that this can be done using getters/setters, but I am not too sure.

Faisal Syed
  • 921
  • 1
  • 11
  • 25

2 Answers2

1

You could do it like this:

class ViewController: UIViewController {

    var appDelegate:AppDelegate?
    var managedObjectContext:NSManagedObjectContext?

    override func viewDidLoad() {
        super.viewDidLoad()

        appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
        managedObjectContext = appDelegate?.managedObjectContext
    }
David S.
  • 6,567
  • 1
  • 25
  • 45
  • Huh, that's one way. I was wondering if I could set it all up by making them instances on ViewController without amending them in viewDidLoad – Faisal Syed Aug 25 '16 at 20:25
  • I would caution you about trying to access the MOC too early in the application lifecycle. I've seen lots of issues with that. Generally MOCs should be short lived. If you have multiple view controllers, you should create a separate MOC per VC, either with a parent-child model or with a common Persistent Store Coordinator. – David S. Aug 25 '16 at 20:47
  • I see, that makes sense. In an actual application that sounds like something I'd do, however I was just curious if what I was asking for was possible. – Faisal Syed Aug 25 '16 at 20:54
1

I had to change the appDelegate to a variable from a constant, and then make my managedObjectContext a lazy variable so that I had access to "self". I also had to include the type NSManagedObjectContext like so :

var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
lazy var managedObjectContext: NSManagedObjectContext = self.appDelegate.managedObjectContext
Faisal Syed
  • 921
  • 1
  • 11
  • 25