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;
UIApplicationDelegate does not have a member called managedObjectContext
var appDelegate = UIApplication.sharedApplication().delegate
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:
The object that is returned is only known to implement the methods described by the
UIApplicationDelegate protocol. That does not include