AppDelegate中的NSTimer不会更新UIViewController中的UILabel

时间:2013-05-14 02:47:51

标签: objective-c nsstring uilabel nstimer appdelegate

我的目标是在app委托中启动一个计时器,并使用它来调用其他视图控制器中的方法。调用这些方法时,它们将更新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);
}

1 个答案:

答案 0 :(得分:0)

每次打电话:

GreyViewController *greyClass = [[GreyViewController alloc] init];

在你的“updateLabel”方法中(即每两秒钟)你要实例化一个新的GreyViewController。您很可能 想要这样做。

相反,实例化/创建一次(或在故事板或XIB文件中创建)并更新连接到插座的标签。

相关问题