我的目标是在应用程序委托中启动一个计时器并使用它来调用其他视图控制器中的方法。当这些方法被调用时,它们将更新 UILabel 的文本。我正在主线程上执行该方法,但我无法弄清楚为什么 UILabel 没有被更新。我知道正在调用视图控制器中的方法,但 UILabel 没有得到更新。我还在 Interface Builder 中验证了 IBOutlet 连接。我正在使用故事板来布置我的视图并将视图控制器附加到这些视图。我究竟做错了什么?
在我的 AppDelegate.m 中:
#import "AppDelegate.h"
#import "GreyViewController.h"
@interface AppDelegate ()
@property (nonatomic) int counter;
@property (strong, nonatomic) GreyViewController *greyClass;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSTimer *timer;
timer = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(performOnMain)
userInfo:nil
repeats:YES];
return YES;
}
- (GreyViewController *)greyClass {
if (!_greyClass) {
_greyClass = [[GreyViewController alloc] init];
}
return _greyClass;
}
- (void)performOnMain {
[self performSelectorOnMainThread:@selector(updateLabel) withObject:nil waitUntilDone:YES];
}
- (void)updateLabel {
self.counter++;
NSLog(@"appdelegate counter %i", self.counter);
[self.greyClass updateGreyLabel:[NSString stringWithFormat:@"%i", self.counter]];
}
@end
GreyViewController.h 是:
#import <UIKit/UIKit.h>
@interface GreyViewController : UIViewController
@property (strong, nonatomic) NSString *greyString;
@property (weak, nonatomic) IBOutlet UILabel *greyLabel;
- (void)updateGreyLabel:(NSString *)string;
@end
我的 GreyViewController.m 中的方法:
- (void)updateGreyLabel:(NSString *)string {
self.greyLabel.text = string;
NSLog(@"greyviewcontroller string %@", string);
}