Lin*_*ros 0 class objective-c uilabel ios
我一直在尝试通过从AppDelegate.m到MainViewController.m的方法调用来更新UILabel一段时间.我真的不明白为什么这不起作用.该方法被称为allright,一切正常,除了最后一点更改/更新标签文本.
在applicationDidBecomeActive在AppDelegate中调用该方法updateLabelMethod在MainViewController它处理数据和更新标签.
MainViewController.h
UILabel *daysResultOutlet;
@interface MainViewController : UIViewController <FlipsideViewControllerDelegate>
@property (strong, nonatomic) IBOutlet UILabel *daysResultOutlet;
@end
@interface MainViewController ()
- (void) updateLabelMethod;
@end
Run Code Online (Sandbox Code Playgroud)
MainViewController.m
@synthesize daysResultOutlet;
- (void) updateLabelMethod {
NSString *value = @"test";
NSLog(@"Testing to print value: %@",value);
[daysResultOutlet setText:value]; //insert in label
}
Run Code Online (Sandbox Code Playgroud)
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!
}
Run Code Online (Sandbox Code Playgroud)
该标签没有更新或者通过跨类中的方法调用updateLabelMethod或通过mvsAsObj.daysResultOutlet.text = @"update!!";,然而,该方法被调用和priting值:LOG: Testing to print value: test.此外,如果我从MainViewController中调用此方法:[self updateLabelMethod]一切正常.
我已经尝试了基本上所有的解决方案,但问题是,我在这里做的是直接几个Stackoverflow问题,所以我不知道如何继续.我正在使用故事板.
还有什么想法?
感谢Ryan Poolos指出让我的控制器监听UIApplicationDidBecomeActiveNotification而不是从AppDelegate调用方法的可能性.这就是我最终做到的方式:
在MainViewControll中,ViewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(becomeActive:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
- (void)becomeActive:(NSNotification *)notification {
NSLog(@"active");
}
Run Code Online (Sandbox Code Playgroud)
清理通知
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
Run Code Online (Sandbox Code Playgroud)