How do I get a reference to the app delegate in Sw

2020-01-23 10:33发布

How do I get a reference to the app delegate in Swift?

Ultimately, I want to use the reference to access the managed object context.

标签: swift
18条回答
相关推荐>>
2楼-- · 2020-01-23 10:43

it is very simple

App delegate instance

let app = UIApplication.shared.delegate as! AppDelegate

you can call a method with one line syntax

app.callingMethod()

you can access a variable with this code

app.yourVariable = "Assigning a value"
查看更多
forever°为你锁心
3楼-- · 2020-01-23 10:46

In my case, I was missing import UIKit on top of my NSManagedObject subclass. After importing it, I could remove that error as UIApplication is the part of UIKit

Hope it helps others !!!

查看更多
家丑人穷心不美
4楼-- · 2020-01-23 10:48

Here is the Swift 2.0 version:

let delegate = UIApplication.sharedApplication().delegate as? AppDelegate

And to access the managed object context:

    if let delegate = UIApplication.sharedApplication().delegate as? AppDelegate {

        let moc = delegate.managedObjectContext

        // your code here

    }

or, using guard:

    guard let delegate = UIApplication.sharedApplication().delegate as? AppDelegate  else {
        return
    }

    let moc = delegate.managedObjectContext

    // your code here
查看更多
男人必须洒脱
5楼-- · 2020-01-23 10:48

As of iOS 12.2 and Swift 5.0, AppDelegate is not a recognized symbol. UIApplicationDelegate is. Any answers referring to AppDelegate are therefore no longer correct. The following answer is correct and avoids force-unwrapping, which some developers consider a code smell:

import UIKit

extension UIViewController {
  var appDelegate: UIApplicationDelegate {
    guard let appDelegate = UIApplication.shared.delegate else {
      fatalError("Could not determine appDelegate.")
    }
    return appDelegate
  }
}
查看更多
女痞
6楼-- · 2020-01-23 10:50

I use this in Swift 2.3.

1.in AppDelegate class

static let sharedInstance: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

2.Call AppDelegate with

let appDelegate = AppDelegate.sharedInstance
查看更多
虎瘦雄心在
7楼-- · 2020-01-23 10:52

In Swift 3.0 you can get the appdelegate reference by

let appDelegate = UIApplication.shared.delegate as! AppDelegate
查看更多
登录 后发表回答