【问题标题】:Update UILabel from applicationDidBecomeActive?从 applicationDidBecomeActive 更新 UILabel?
【发布时间】: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


    【解决方案1】:

    第一:

    [[MyViewController alloc] reloadButtonAction];
    

    没有意义。您分配内存,而不初始化对象。然后你想在它上面调用一个方法。不工作 为它使用一个实例:

    [myViewControllerInstance reloadButtonAction];
    

    在您的应用委托中,您应该有对根控制器实例的引用,如果该对象包含 reload 方法,请使用该实例。

    注意: Alloc 仅在内存中为与 MyViewController 实例大小相同的对象保留空间。一个 init 方法将填充它。

    【讨论】:

    • 没问题。让他们来! ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多