2014-11-23 1 views
1

UILabel의 텍스트를 변경하는 코드가 있는데 앱을 처음 실행할 때 제대로 작동하지만 앱을 닫을 때 (앱이 배경으로 이동) 다시 열면 UILabel이 nil이고 텍스트를 다시 설정할 수 없습니다.Swift UILabel이 앱이 백그라운드로 전환 할 때 nil (오류)

텍스트는 viewDidLoad() 함수에서 UILabel의 설정과 나는 다시 UILabel 텍스트를 설정하는 applicationWillEnterForeground 기능에 viewDidLoad()를 호출한다 - 그것은 오류 fatal error: unexpectedly found nil while unwrapping an Optional value을 제공 충돌 할 때 그건.

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

그리고 ViewController.swift에 : 나는 그것을 발견 된 nil가 여기에 UILabel

입니다 AppDelegate.swift의 코드의 일부입니다 디버깅

func refresh() { 
    self.viewDidLoad() 
} 

UILabel이됩니다 왜 당신이 어떤 생각을 가지고 있습니까 nil 앱이 백그라운드로 이동할 때?

+1

에 기능을 추가 'applicationWillEnterForeground'에서보기 컨트롤러에 대한 참조를 보내고 있습니까? 이 방법 여기 – Paulw11

+0

의 코드를 보여주십시오 함수 입니다'FUNC applicationWillEnterForeground (응용 프로그램 : UIApplication) {. 의 ViewController()() 를 새로}'과의 ViewController에서 : 'FUNC 새로 고침() { self.viewDidLoad() }' – sachalondon

+0

코드를 포함하도록 질문을 편집해야합니다. 태그 아래의 "수정"링크를 참조하십시오. 'ViewController' 란 무엇입니까? 속성입니까? 어떻게 설정 되나요? 또한 리팩토링해야합니다 - 결코'viewDidLoad'를 호출해서는 안됩니다 - 설정 코드를 다시 사용하고 그 코드를 다른 함수로 옮기고'viewDidLoad'를 호출하면 – Paulw11

답변

1

오히려 앱 위임에서 뷰 컨트롤러에 대한 참조를 보유하는 것보다, 단순히보기 컨트롤러 전경 항목 이벤트에 가입해야하는 것이 좋습니다 - 추가하려면 viewDidLoad에서

을 다음

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("enteringForeground:"), 
    name: UIApplicationWillEnterForegroundNotification, object: nil) 

당신이 명시 적으로 viewDidLoad`가`viewWillAppear` 등 당신이 어떻게 겟하는`전화를해서는 안됩니다 당신의 ViewController

func enteringForeground(notification: NSNotification) { 
    // Whatever you need to do to refresh UI 
    // DO NOT CALL viewDidLoad 
} 

deinit { 

    NSNotificationCenter.defaultCenter().removeObserver(self) 

} 
+0

보기 컨트롤러가 할당 해제되기 전에 옵저버를 제거해야합니다.NSNotificationCenter 문서에서 : "addObserverForName : object : queue : usingBlock :'에 의해 지정된 객체가 할당 해제되기 전에'removeObserver :'또는'removeObserver : name : object :'를 호출해야합니다." –

관련 문제