2015-01-19 4 views
0

을 위해 내가 라벨에 텍스트를 변경하기 위해 노력하고있어 발견됩니다applicationWillEnterForeground 앱 전경를 입력하지만 난 항상 얻을 때 전무가 textLabel라는

치명적인 오류 : 예기치 않게 발견하는 옵션 값을 풀기 동안 전무

ViewController.swift 

    @IBOutlet var textLabel: UILabel! 

    func showLabel() { 
     textLabel.text = "Welcome back" 
    } 

AppDelegate.swift 

func applicationWillEnterForeground(application: UIApplication) { 
     ViewController().showLabel() 
    } 

어떤 문제를 해결하는 방법?

+0

가 해당 뷰 컨트롤러가 을로드 뷰 했습니까? – Wain

+0

가능한 복제본 [didBecomeActive()에서 선택 값을 래핑하지 않을 때] (http://stackoverflow.com/questions/28016699/nil-when-unwrapping-an-optional-value-in-didbecomeactive) –

+0

옙 이것이 내 것이 었습니다. 해결책 : http://stackoverflow.com/questions/28016699/nil-when-unwrapping-an-optional-value-in-didbecomeactive하지만 이전에 찾지 못했습니다. 오늘 질문했습니다 – chrisco

답변

1

앞에서 설명한대로 post에서보기 컨트롤러의 viewDidLoad 함수에서 레이블을 초기화해야합니다.

사실, 사용자가 applicationWillEnterForeground에있을 때보기 컨트롤러가 아직 초기화되지 않았으므로 레이블 textLabel이 null (nil)이고 null 개체의 속성에 액세스하려고합니다 (오류의 원인).

ViewController.swift :

@IBOutlet var textLabel: UILabel! 

func viewDidLoad() { 
    textLabel.text = "Welcome back" 
} 
+0

작동하지 않습니다. 나는 오류를보고 나서 그것을 seceond했지만 도움이되지 않았다 – chrisco

1

문제는, 당신은 당신의 ViewController의 새로운 인스턴스를 생성하고 여기에 데이터를 설정하려고합니다.

즉 기존의 하나가 답변을

+0

나는 그것을 알고 있지만 어떻게 내가 기존의 것을 얻을 수 있습니까? (응용 프로그램 : 응용 프로그램 : UIApplication, didFinishLaunchingWithOptions launchOptions : [NSObject : AnyObject]?) -> Bool { // 응용 프로그램 시작 후 사용자 지정을위한 재정의 포인트. return true } – chrisco

+0

@chrisco : 스토리 보드에서 ViewController를 설정하는 경우 역방향 메커니즘을 사용하십시오 (뷰 컨트롤에서 앱 대리자의 데이터를 가져 오는 것을 의미). 다른 경우 ViewController를 응용 프로그램의 rootViewController 속성으로 설정하십시오. –

2

덕분에 (당신은 didFinishLaunchingWithOptions:에 생성)를 사용하는 대신! 나는

있는 viewDidLoad

NSNotificationCenter.defaultCenter().addObserver(self, selector: "showLabel", name: UIApplicationDidBecomeActiveNotification, object: nil) 

으로 관리하고 AppDelegate에

func showLabel() {} 

에 기반으로 : Nil when unwrapping an Optional Value in didBecomeActive()