Programming

Swift에서 앱 델리게이트에 대한 참조를 얻으려면 어떻게해야합니까?

procodes 2020. 2. 28. 19:34
반응형

Swift에서 앱 델리게이트에 대한 참조를 얻으려면 어떻게해야합니까?


Swift에서 앱 델리게이트에 대한 참조를 얻으려면 어떻게해야합니까?

궁극적으로 참조를 사용하여 관리 객체 컨텍스트에 액세스하고 싶습니다.


다른 솔루션은 응용 프로그램의 대리자에 대한 참조를 얻는다는 점에서 맞지만 관리되는 객체 컨텍스트와 같이 UIApplication의 하위 클래스에 의해 추가 된 메서드 나 변수에 액세스 할 수는 없습니다. 이 문제를 해결하려면 간단히 "AppDelegate"로 다운 캐스트하거나 UIApplication 서브 클래스를 호출하십시오. 이렇게 :

스위프트 3.x (Xcode 8에서 도입)

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

스위프트 1.2-2.x (Xcode 6.3에서 도입)

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

스위프트 <1.2

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

스위프트 4.2

스위프트에서는 VC에서 쉽게 액세스 할 수 있습니다.

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

편의 생성자

코드 끝에 AppDelegate 클래스에 추가

스위프트 5

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

수업에서 AppDelegate 참조를 사용하려면?


AppDelegate 메소드 호출

appDelegate (). setRoot ()


Objective-C와 거의 동일합니다.

let del = UIApplication.sharedApplication().delegate

이것은 OS X에 사용될 수 있습니다

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

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

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

그리고 관리 객체 컨텍스트에 액세스하려면 :

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

        let moc = delegate.managedObjectContext

        // your code here

    }

또는 guard를 사용하여 :

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

    let moc = delegate.managedObjectContext

    // your code here

여기에 나와있는 것에서 Appart, 내 경우에는 UIKit 가져 오기가 누락되었습니다.

import UIKit

스위프트 <3

Ex 용 AppDelegate 클래스에서 메소드 작성

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

전 다른 곳으로 불러

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

빠른> = 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.

}

1) 확인하십시오 import UIKit

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


클래스 이름을 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

매우 간단합니다

앱 대리자 인스턴스

let app = UIApplication.shared.delegate as! AppDelegate

한 줄 구문으로 메소드를 호출 할 수 있습니다

app.callingMethod()

이 코드로 변수에 액세스 할 수 있습니다

app.yourVariable = "Assigning a value"

필자의 경우 하위 클래스 import UIKit위에 누락되었습니다 NSManagedObject. 가져온 후에 UIApplication해당 오류를 제거 할 수 있습니다.UIKit

그것이 다른 사람들을 돕기를 바랍니다!


나는 이것을 스위프트 2.3에서 사용한다.

1. AppDelegate 클래스에서

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

2. 전화 걸기

let appDelegate = AppDelegate.sharedInstance

extension AppDelegate {

    // MARK: - App Delegate Ref
    class func delegate() -> AppDelegate {
        return 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
  }
}

Swift 3.0에서는 다음을 통해 appdelegate참조를 얻을 수 있습니다.

let appDelegate = UIApplication.shared.delegate as! 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-app-delegate-in-swift



반응형