2011-12-29 50 views

回答

2

這聽起來像你採取了錯誤的做法。由於位置管理器是視圖控制器上的一個實例變量,它應該是視圖控制器指示它停止 - 而不是應用程序委託。

這就是Cocoa/UIKit/Objective-C如何設計工作,其他任何事情都是艱難的戰鬥。

也許這樣的事情在你的viewController:

@implementation MyViewController 

- (id)init 
{ 
    ... 

    self.locationManager = [[CLLocationManager alloc] init]; 
    locationManager.delegate = self; 
    [self.locationManager startUpdatingLocation]; 

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil]; 

    ... 
} 

- (void)dealloc 
{ 
    [self.locationManager stopUpdatingLocation]; 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 

    ... 
} 

- (void)applicationWillEnterForeground:(NSNotification *)notif 
{ 
    [self.locationManager startUpdatingLocation]; 
} 


- (void)applicationDidEnterBackground:(NSNotification *)notif 
{ 
    [self.locationManager stopUpdatingLocation]; 
} 

@end 

但是,爲了回答您的視圖控制器內您的具體問題,你可以用它來訪問應用程序的委託:

[UIApplication sharedApplication].delegate 

這會讓你告訴它關於視圖控制器。但要小心,因爲你可能會造成內存泄漏!

您需要確保委託不保留您的視圖控制器,否則它將永遠不會被釋放。並且您需要確保在解除分配視圖控制器時委託人對視圖控制器的引用設置爲nil。

一般而言,您應該避免讓應用程序委託對任何特定的視圖控制器都瞭解。

+0

感謝您的幫助,但我的問題是相反的方式。我需要一種方法在appdelegate中引用我的viewController,以便在調用applicationdidenterbackground方法時向viewcontroler發送消息。您發佈的代碼我認爲可以做得很好,但從appdelegate向viewcontroller發送消息告訴viewcontroller appwillenterbackground消息已發送至appdelegate會更簡單。謝謝 – Mppl 2011-12-31 01:30:13

+0

您的視圖控制器需要發送一條消息給應用程序委託來告訴它關於控制器。例如:'[UIApplication sharedApplication] .delegate.myViewController = self;'但是除非你做得對,這會導致內存泄漏和/或崩潰,所以儘量不要做,除非你有一個很好的理由(也許你可以解釋爲什麼在你的問題)。 – 2011-12-31 08:53:28

+0

原因很簡單我在我的viewcontroller中有一個CLLocationManager實例,當視圖加載時我希望它啓動到位置,並且我必須告訴它在某個時候停止......我的viewcontroller中的其他委託方法是viewdidunload,但是我不想在應用程序進入後臺時停止更新位置,所以我不得不以某種方式引用appwillterminate方法中的CLLocationmanager實例(在我的appdelegate中實現),以將其指向stopUpdatingLocation。 – Mppl 2012-01-01 23:11:02

0

當應用程序即將進入後臺時,您的viewcontroller中是否未調用viewWillDisappear委託方法?

+0

不,這不是......我想在那裏......將是有用的 – Mppl 2012-01-02 21:53:10

相關問題