我有一个对我的应用委托(delegate)的引用
let appDel: AppDelegate = (UIApplication.sharedApplication().delegate) as AppDelegate
这工作得很好,但是下面这行代码给出了一个错误:
let context: NSManagedObjectContext = appDel.managedObjectContext
它给了我以下错误:
'vctGebruikers.Type' does not have a member named 'appDel'
我像这样在类(class)下面声明了它们:
class vctGebruikers: UIViewController, UITableViewDelegate, UITableViewDataSource {
let appDel: AppDelegate = (UIApplication.sharedApplication().delegate) as AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
}
奇怪的是,当我将代码粘贴到 viewDidLoad
或函数中时,代码运行正常。而且我无法弄清楚问题是什么。
我该如何解决这个错误?
编辑: 我还需要在此处访问上下文:
let results: NSArray = context.executeFetchRequest(request, error: nil)
感谢@Antonio,这就是我的工作,但现在我无法访问上下文和 appDel
init(coder aDecoder: NSCoder!) {
let appDelegate = (UIApplication.sharedApplication().delegate) as AppDelegate
self.appDel = appDelegate
self.context = appDelegate.managedObjectContext
super.init(coder: aDecoder)
}
最佳答案
在所有类属性都已初始化之前,在 swift 中您不能引用 self
。
您在这一行中隐含地使用了 self
:
let context: NSManagedObjectContext = appDel.managedObjectContext
解决方案是在初始化器中初始化它们,但使用类似:
let appDelegate = (UIApplication.sharedApplication().delegate) as AppDelegate
self.appDel = appDelegate
self.context = appDelegate.managedObjectContext
另请阅读 here,这是几天前在 SO 上提出的一个类似问题。
关于ios - className.type 没有名为 'appDel' 的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24685969/