2011-02-16 64 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