0

I have an Objective C project and am trying to call the AppDelegate from a Swift view controller. This code is not working:

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

let managedContext = appDelegate.managedObjectContext
Paulw11
  • 108,386
  • 14
  • 159
  • 186
John
  • 538
  • 4
  • 18
  • 1
    Define "not working". Have you added a bridging header? – Paulw11 Sep 02 '16 at 00:03
  • I added a bringing header that includes #import "AppDelegate.h" which eliminated the error on AppDelegate. Now I'm getting an error on: let managedContext... Instance member 'appDelegate" cannot be used on type "ViewController" (The name of the class is ViewController.swift) Thanks for the help. – John Sep 02 '16 at 18:04

3 Answers3

0

Have you added the brining header to your project?

On top of that, if you do, make sure you import "AppDelegate.h" into the bridging header.

The in the swift class you should be able to call it with:

guard let appDele = UIApplication.sharedApplication().delegate as? AppDelegate else {
    fatalError("Unable to reference App Delegate, check settings and riding header")
}
let managedContext = appDele.managedObjectContext
Adrian Sluyters
  • 2,186
  • 1
  • 16
  • 21
  • "guard" causes: Consecutive declarations on a line must be separated by ':' AND Expected declaration ERROR MSGS. Adding a ; doesn't solve the issue. Thanks for the help – John Sep 02 '16 at 18:09
0

There is another way. Include "AppDelegate.h" into the bridging header and make sure you resolve any errors.

Then create an Objective C object that has one method that returns the app delegate object. All it needs to do is return the app delegate pointer. The object file must also include "AppDelegate.h" and resolve any errors.

-(yourAppDelegate*)giveMeTheAppDelegate{
 return yourAppDelegate;
}

Then in the Swift file, you can now create the object and reference any methods.

let theObj = iAmAnObjectiveCObjectWithOneMethod()
let theDelegate = theObj.giveMeTheAppDelegate()
theDelegate?.thisMethodDisplaysText("hello")
Aron Nelson
  • 838
  • 1
  • 9
  • 17
0

Add "(ProjectName)-Swift.h" in .m file

Add @class AppDelegate in .h file

Add variables in AppDelegate file with '@objc' extension so that it can be accessed in Objective C as well as *** file.

Sheetal Shinde
  • 489
  • 5
  • 7