ClassName.type does not have a member called 'appDel'

I have a link to my application delegate

let appDel: AppDelegate = (UIApplication.sharedApplication().delegate) as AppDelegate 

This works fine, but this line of code gives an error:

 let context: NSManagedObjectContext = appDel.managedObjectContext 

This gives me the following error:

 'vctGebruikers.Type' does not have a member named 'appDel' 

I declared them right under my class as follows:

 class vctGebruikers: UIViewController, UITableViewDelegate, UITableViewDataSource { let appDel: AppDelegate = (UIApplication.sharedApplication().delegate) as AppDelegate let context: NSManagedObjectContext = appDel.managedObjectContext } 

It is strange when I paste the code into viewDidLoad or into a function, the code just works fine. And I can’t understand what the problem is. How can I solve this error?

EDIT: I also need to use the context here:

 let results: NSArray = context.executeFetchRequest(request, error: nil) 

This is what I got thanks to @Antonio, but now I was not able to access the context and appDel

 init(coder aDecoder: NSCoder!) { let appDelegate = (UIApplication.sharedApplication().delegate) as AppDelegate self.appDel = appDelegate self.context = appDelegate.managedObjectContext super.init(coder: aDecoder) } 
+8
ios swift
source share
2 answers

In swift, you cannot reference self until all the properties of the class are initialized. You implicitly use self on this line:

 let context: NSManagedObjectContext = appDel.managedObjectContext 

The solution is to initialize them in the initializer, but using something like:

 let appDelegate = (UIApplication.sharedApplication().delegate) as AppDelegate self.appDel = appDelegate self.context = appDelegate.managedObjectContext 

Also read here , a similar question was asked a couple of days ago on SO.

0
source share

One way to create context is to drill, not with AppDelegate

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { if let vc = window?.rootViewController as? UIViewController { vc.context = self.managedObjectContext} 

`

And in your view the controller, tell it to dynamically populate

var context: NSManagedObjectContext!

Also remember to call import CoreData wherever you use the specified objects.

Another final method: use closure so that your link happens at runtime: var context: NSManagedObjectContext { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate return appDelegate.managedObjectContext } var context: NSManagedObjectContext { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate return appDelegate.managedObjectContext }

0
source share

All Articles