从AppDelegate访问View Controller的属性

时间:2014-10-09 01:40:46

标签: ios objective-c appdelegate

我目前有一个Xcode项目,我正在使用Storyboard。在我的AppDelegate中,我需要设置一些属性,这些属性包含在其他View Controllers的.h文件中,以响应应用程序收到的通知。

如何在AppDelegate中实例化这些视图控制器的对象,以便我可以访问和修改它们的属性?

1 个答案:

答案 0 :(得分:1)

应用程序委托有一些方法可以获得正确的vc并与之通信,但更好的设计是让信息以相反的方式流动,让视图控制器请求信息并更新自己的属性。

要执行此操作,当应用代表收到通知时,请让其发布相应的NSNotification(通过NSNotificationCenter)。关心更改的视图控制器可以将自己添加为此通知的观察者并获取信息。他们怎么能得到它?几种方式:

教科书的方式是在应用程序上有一个模型,可能是一个具有与视图控制器相关的属性的单例。想法二是有效地让你的应用程序通过赋予vcs可以查询的属性来委托模型。最后一点,postNotificationName:(NSString *)notificationName object:(id)notificationSender userInfo:(NSDictionary *)userInfo上的userInfo参数可以向观察者传达信息。

编辑 - NSNotificationCenter非常易于使用。它是这样的:

在AppDelegate.m中,当您收到外部通知时:

// say you want a view controller to change a label text and its
// view's background color
NSDictionary *info = @{ @"text": @"hello", @"color": [UIColor redColor] };
[[NSNotificationCenter defaultCenter] postNotificationName:@"HiEverybody" object:self userInfo:info];

在SomeViewController.m中,订阅消息:

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(observedHi:)
                                                 name:@"HiEverybody"
                                               object:nil];
}

// unsubscribe when we go away
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// this method gets run when the notification is posted
// the notification's userInfo property contains the data that the app delegate provided
- (void)observedHi:(NSNotification *)notification {

    NSDictionary *userInfo = notification.userInfo;
    self.myLabel.text = userInfo[@"text"];
    self.view.backgroundColor = userInfo[@"color"];
}
相关问题