I want to use Core Data in my Swift iOS app, but how can I call Core Data's managedObjectContext from within any ViewControllers?
Suppose that I want to call this method which is oft-used in Objective-C:
self.managedObjectContext = ((AppDelegate *) [UIApplication sharedApplication].delegate).managedObjectContext;
However, when I wrote the following code in my Swift file, it got the error: UIApplicationDelegate does not have a member called managedObjectContext
.
var appDelegate = UIApplication.sharedApplication().delegate
println(appDelegate.managedObjectContext)
Why does this get the error? Because I checked on Core Data when creating the app, the template automatically defined the managedObjectContext variable in AppDelegate.swift
file.
So what is missing? I use Xcode 6 beta 5.
The recommended way to do this is to pass the NSManagedObjectContext
into the first view controller, and from then on to subsequent view controllers. This is what the Apple Xcode (objective-c) templates do. The object that implements UIApplicationDelegate
creates the NSManagedObjectContext
and it's dependancies, and then sets that object as the managedObjectContext property on the first view controller.
The reason you are getting this compilation error is that the UIApplicationDelegate
protocol does not define the property managedObjectContext
. When you attempt to access the object that is the application's delegate:
UIApplication.sharedApplication().delegate
The object that is returned is only known to implement the methods described by the UIApplicationDelegate
protocol. That does not include managedObjectContext
.