2011-02-16 82 views
1

我想通過單擊重新加載按鈕來更新UILabel。另外,我想在後臺更新標籤,因爲它是從我的網站通過XML獲取新數據。當然,應用程序打開時自動更新標籤會很好。並有我的問題:從applicationDidBecomeActive更新UILabel?

當用戶手動點擊按鈕時,我能夠使它工作良好。但我不明白如何通過「applicationDidBecomeActive」調用我的方法來做同樣的事情。我試圖以同樣的方式來做,但它顯然不起作用,因爲我的標籤返回零。

我想我的理解存在問題,解決方案應該很容易。感謝您的輸入!注意:我是Objective-C的初學者,有時會遇到「簡單」問題。 ;-)

下面是重要的部分代碼摘要:

的AppDelegate

- (void)applicationDidBecomeActive:(UIApplication *)application { 
    [[MyViewController alloc] reloadButtonAction]; 
} 

MyViewController

@synthesize label 

- (void)reloadButtonAction { 
    [self performSelectorInBackground:@selector(updateData) withObject:nil]; 
} 

- (void)updateData { 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    // Parse the XML File and save the data via NSUserDefaults 
    [[XMLParser alloc] parseXMLFileAtURL]; 

    // Update the labels 
    [self performSelectorOnMainThread:@selector(updateLabels) withObject:nil waitUntilDone:NO]; 

    [pool release]; 
} 

- (void)updateLabels { 
    NSUserDefaults *variable = [NSUserDefaults standardUserDefaults]; 
    myLabel.text = [variable stringForKey:@"myLabelText"]; 

    // myLabel is nil when calling all of this via AppDelegate 
    // so no changes to the myLabel are done in that case 
    // but: it works perfectly when called via button selector (see below) 
    NSLog(@"%@",myLabel.text); 
} 

-(void)viewDidLoad { 
    // Reload button in the center 
    UIButton *reloadButton = [UIButton buttonWithType:UIBarButtonSystemItemRefresh]; 
    reloadButton.frame = CGRectMake(145,75,30,30); 
    [reloadButton setTitle:@"" forState:UIControlStateNormal]; 
    [reloadButton addTarget:self action:@selector(reloadButtonAction) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:reloadButton]; 
} 

回答

3

第一:

[[MyViewController alloc] reloadButtonAction]; 

沒有意義。您分配內存,而不初始化對象。然後你想調用一個方法。不工作 使用實例吧:

[myViewControllerInstance reloadButtonAction]; 

在你的應用程序代理,你應該有你的rootcontroller實例的引用如果是這樣的對象包含重載方法,使用該實例。

注意: Alloc只爲內存中的空間保留一個尺寸爲MyViewController實例大小的對象。 init方法將填充它。

+0

你真的很好!這已經解決了我的問題! – andreas 2011-02-16 17:39:11