【发布时间】:2011-02-16 17:21:26
【问题描述】:
我想通过单击重新加载按钮来更新 UILabel。此外,我想在后台更新标签,因为它通过 XML 从我的网站获取新数据。当然,在打开应用程序时自动更新标签会很好。还有我的问题:
当用户手动单击按钮时,我能够使其正常工作。但我不明白如何通过“applicationDidBecomeActive”调用我的方法来做同样的事情。我尝试以相同的方式执行此操作,但显然它不起作用,因为我的标签返回 nil。
我想我的理解有问题,解决方案应该很容易。感谢您的输入!注意:我是 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];
}
【问题讨论】:
标签: iphone objective-c background uilabel