Carlos Maria Caraccia
Carlos Maria Caraccia

Reputation: 500

Cannot create a reference to AppDelegate Class in Swift

I am a beginner programmer and I am targeting OSX. I want to create a reference to the managed object context property thats inside AppDelegate, to use it in a Core Data project I'm creating

I try

let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let aVariable = appDelegate.someVariable

or make it mutable, typing var instead of let. Can anyone give me some help, please?

Thanks

Upvotes: 1

Views: 4107

Answers (2)

Mick MacCallum
Mick MacCallum

Reputation: 130193

The problem is that you're trying to use code from the iOS frameworks in the OS X application. You need NSApplication, UIApplication's OS X counterpart.

let appDelegate = NSApplication.sharedApplication().delegate as AppDelegate
let aVariable = appDelegate.someVariable

Upvotes: 1

Antonio
Antonio

Reputation: 72750

For macos apps you have to use NSApplication instead of UIApplication:

let appDelegate = NSApplication.sharedApplication().delegate as AppDelegate

I presume you are using the Cocoa Application template in Xcode, and you have enabled the Use Core Data checkbox - in that case NSApplication will be generated with a managedObjectContext property, defined as follows:

var managedObjectContext: NSManagedObjectContext? {
    ...
}

That's a computed property, returning an optional, so you have to unwrap it before using.

Upvotes: 6

Related Questions