2011-05-02 51 views
1

在Facebook的iPhone應用程序中,每次應用程序激活時都會刷新新聞訂閱源。我想做類似的事情,但我擔心競賽狀況。我的應用程序的一般引導如下:當應用程序變爲活動狀態時刷新視圖中的競爭條件

UIApplicationDelegate

- (void)applicationDidFinishLaunching:(UIApplication*)application 
{ 
    [window addSubview:[self.navigationController view]; 
    [window makeKeyAndVisible]; 
} 

- (void)applicationDidBecomeActive:(UIApplication*)application 
{ 
    [rootViewController refresh]; 
} 

RootViewController的

#pragma mark custom 

- (void)refresh 
{ 
    if (self.newsFeedModel == nil) { 
    self.newsFeedModel = [[NewsFeedModel alloc] initWithDelegate:self]; 
    } 
    [self.newsFeedModel request]; 
} 

#pragma mark UIViewController 

- (void)viewDidLoad 
{ 
    // initialize the table 
    // add subviews and whatnot 
} 

#pragma mark NewsFeedDelegate 

- (void)newsFeedSucceeded:(NSMutableArray*)feed 
{ 
    // reload table view with new feed data 
} 

NSLog到處之後,我決定操作順序爲:

  1. 的applicationDidFinishLaunching
  2. applicationDidBecomeActive
  3. 刷新
  4. viewDidLoad中
  5. newsFeedSucceeded

注意如何根查看已經加載刷新之前被調用。當我們忙於查詢服務器時,根視圖會加載。當服務器響應時,根視圖將填充該提要。這在大多數情況下適用,因爲網絡操作需要很長時間。但是,如果網絡操作完成速度快於視圖可以加載,那麼我將嘗試在視圖加載之前構建新聞饋送。這會很糟糕。解決這種競爭狀況的最佳Cocoa Touch練習是什麼?我只是設置一堆標誌來確定我們所處的狀態,並根據狀態刷新新聞提要,但是我想知道是否在Cocoa Touch中內置了事件來處理這個問題。

回答

1

我想你想看看applicationWillEnterForeground:取而代之。

applicationDidBecomeActive:可以在應用程序仍在前臺運行時調用。例如,如果在您的應用處於前臺並且用戶將其解除的情況下發送了短信,則會調用applicationDidBecomeActive:。

您可以使用NSNotificationCenter在您的RootViewController中訂閱UIApplicationWillEnterForegroundNotification事件。我會在RootViewController的initWithNibName中執行此操作,或者使用您所使用的任何init方法。

現在你只需要在2個地方調用刷新。一旦在viewDidLoad結束時,再次調用applicationWillEnterForeground:時。

這應該可以解決您的種族問題。由於RootViewController在知道可以這樣做時正在處理它自己的刷新。

RootViewController的

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if(self) { 
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil]; 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    // initialize the table 
    // add subviews and whatnot 
    [self refresh]; 
} 


- (void)applicationWillEnterForeground:(UIApplication *)application { 
    [self refresh]; 
} 

- (void)dealloc 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
    [super dealloc]; 
} 
+0

應用** **將意味着EnterForeground該視圖* *會在屏幕上加載,但它不是* *目前在屏幕上。在表格視圖甚至放到屏幕上之前操作它是否安全? – JoJo 2011-05-02 23:14:53

+0

從newsFeedSucceeded:調用[tableView reload]是很好的。 tableView會通過數據源和委託回調準備好數據。 – jaminguy 2011-05-03 04:44:38