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];
}
你真的很好!這已經解決了我的問題! – andreas 2011-02-16 17:39:11