gpt4 book ai didi

ios - Objective-C : Why can't I update a label from another class (AppDelegate > MainViewController)?

转载 作者:行者123 更新时间:2023-11-28 18:06:29 25 4
gpt4 key购买 nike

一段时间以来,我一直在尝试通过从 AppDelegate.mMainViewController.m 的方法调用来更新 UILabel。我真的不明白为什么这不起作用。 方法被正确调用并且一切正常除了更改/更新标签文本的最后一点。

工作流程

AppDelegateapplicationDidBecomeActive 中调用 MainViewController 中的方法 updateLabelMethod 处理数据和更新标签。

代码

MainViewController.h

UILabel *daysResultOutlet;
@interface MainViewController : UIViewController <FlipsideViewControllerDelegate>
@property (strong, nonatomic) IBOutlet UILabel *daysResultOutlet;
@end

@interface MainViewController ()
- (void) updateLabelMethod;
@end

MainViewController.m

@synthesize daysResultOutlet;
- (void) updateLabelMethod {
NSString *value = @"test";
NSLog(@"Testing to print value: %@",value);
[daysResultOutlet setText:value]; //insert in label
}

AppDelegate.m

#import "AppDelegate.h"
#import "MainViewController.h"

@interface MainViewController ()
@end

- (void)applicationDidBecomeActive:(UIApplication *)application
{
MainViewController *mvsAsObj = [[MainViewController alloc] init];
[mvsAsObj updateLabelMethod]; //running function, value correctly logged but lbl not updated
mvsAsObj.daysResultOutlet.text = @"update!!"; // not working!

}

结果与尝试

标签不会通过跨类方法调用 updateLabelMethod 或通过 mvsAsObj.daysResultOutlet.text = @"update!!"; ,然而,该方法被调用并打印值:LOG: Testing to print value: test。此外,如果我从 MainViewController 中调用此方法:[self updateLabelMethod] 一切正常。

我已经尝试了基本上所有的解决方案,但问题是,我在这里所做的是直接解决几个 Stackoverflow 问题,所以我不知道如何继续。我正在使用 Storyboard。

还有什么想法吗?

最佳答案

感谢 Ryan Poolos 指出让我的 Controller 监听 UIApplicationDidBecomeActiveNotification 而不是从 AppDelegate 调用方法的可能性。这就是我最终这样做的方式:

在 MainViewControll 中,ViewDidLoad

[[NSNotificationCenter defaultCenter] addObserver:self 
selector:@selector(becomeActive:)
name:UIApplicationDidBecomeActiveNotification
object:nil];

- (void)becomeActive:(NSNotification *)notification {
NSLog(@"active");
}

清理通知

- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}

关于ios - Objective-C : Why can't I update a label from another class (AppDelegate > MainViewController)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14407009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com