programing

Swift에서 AppDelegate를 참조하려면 어떻게 해야 합니까?

lovejava 2023. 4. 24. 21:04

Swift에서 AppDelegate를 참조하려면 어떻게 해야 합니까?

Swift에서 AppDelegate를 참조하려면 어떻게 해야 합니까?

최종적으로 이 참조를 사용하여 관리 대상 컨텍스트에 액세스하고 싶습니다.

다른 솔루션은 응용 프로그램 위임자에 대한 참조를 얻는다는 점에서 올바르지만, 관리 개체 컨텍스트와 같이 UIApplication의 하위 클래스에서 추가된 메서드나 변수에 액세스할 수 없습니다.이 문제를 해결하려면 "AppDelegate"로 다운캐스트하거나 UIApplication 서브클래스를 호출하면 됩니다.Swift 3, 4, 5 에서는, 이것은 다음과 같이 행해집니다.

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.someVariable

스위프트 4.2

Swift에서는 VC에서 쉽게 접근할 수 있습니다.

extension UIViewController {
    var appDelegate: AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
   }
}

편리성 컨스트럭터

코드 끝에 AppDelegate 클래스 추가

스위프트 5.7

func appDelegate() -> AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
}

AppDelegate 참조를 코드로 사용할 수 있습니까?


예: setRoot라는 이름의 AppDelegate 메서드를 호출합니다.

appDelegate().setRoot()

OS X에서 사용할 수 있습니다.

let appDelegate = NSApplication.sharedApplication().delegate as AppDelegate
var managedObjectContext = appDelegate.managedObjectContext?

Objective-C와 거의 비슷합니다.

let del = UIApplication.sharedApplication().delegate

Swift 5 버전은 다음과 같습니다.

let delegate = UIApplication.shared.delegate as? AppDelegate

또한 관리 개체 컨텍스트에 액세스하려면 다음과 같이 하십시오.

    if let delegate = UIApplication.shared.delegate as? AppDelegate {

        let moc = delegate.managedObjectContext
        
        // your code here
        
    }

또는 가드 사용:

    guard let delegate = UIApplication.shared.delegate as? AppDelegate  else {
        return
    }

    let moc = delegate.managedObjectContext
        
    // your code here
    

여기에 나와 있는 Appart는 내 경우, UIKit Import를 놓쳤다.

import UIKit

SWIFT < 3

ex의 AppDelegate 클래스에서 메서드를 만듭니다.

func sharedInstance() -> AppDelegate{
        return UIApplication.sharedApplication().delegate as! AppDelegate
    }

전남편에게 다른 곳이라고 불러줘

let appDelegate : AppDelegate = AppDelegate().sharedInstance()

SWIFT > = 3.0

func sharedInstance() -> AppDelegate{
    return UIApplication.shared.delegate as! AppDelegate
}

간단한 조작을 실시합니다.

스위프트 4

// Call the method
(UIApplication.shared.delegate as? AppDelegate)?.whateverWillOccur()

AppDelegate 위치:

// MARK: - Whatever
func whateverWillOccur() {

    // Your code here.

}

여기 의 내선번호가 있습니다.UIApplicationDelegate하드코딩을 피할 수 있습니다.AppDelegate클래스 이름:

extension UIApplicationDelegate {

    static var shared: Self {    
        return UIApplication.shared.delegate! as! Self
    }
}

// use like this:
let appDelegate = MyAppDelegate.shared // will be of type MyAppDelegate
  1. 꼭 확인하세요import UIKit

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

그것은 매우 간단하다.

앱 위임 인스턴스

let app = UIApplication.shared.delegate as! AppDelegate

한 줄 구문을 사용하여 메서드를 호출할 수 있습니다.

app.callingMethod()

이 코드를 사용하여 변수에 액세스할 수 있습니다.

app.yourVariable = "Assigning a value"
extension AppDelegate {

    // MARK: - App Delegate Ref
    class func delegate() -> AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
}

제 경우엔 제가 빠져있었어요import UIKit내 위에NSManagedObject서브클래스Import 후 다음 에러를 제거할 수 있습니다.UIApplication의 일부입니다.UIKit

다른 사람에게 도움이 되길 바랍니다!!!

Swift 2.3에서 사용합니다.

1.in AppDelegate 클래스

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

2. AppDelegate 문의

let appDelegate = AppDelegate.sharedInstance

Swift 3.0에서는,appdelegate에 의한 참조.

let appDelegate = UIApplication.shared.delegate as! AppDelegate

iOS 12.2 및 Swift 5.0에서는AppDelegate인식되는 기호가 아닙니다. UIApplicationDelegate이 질문에 대한 답변은AppDelegate따라서 더 이상 정답이 아닙니다.다음 답변은 정확하며 일부 개발자는 코드 냄새로 간주하는 강제 언랩을 방지합니다.

import UIKit

extension UIViewController {
  var appDelegate: UIApplicationDelegate {
    guard let appDelegate = UIApplication.shared.delegate else {
      fatalError("Could not determine appDelegate.")
    }
    return appDelegate
  }
}

Xcode 6.2 에서는, 이것도 동작합니다.

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

let aVariable = appDelegate.someVariable

언급URL : https://stackoverflow.com/questions/24046164/how-do-i-get-a-reference-to-the-appdelegate-in-swift