【发布时间】:2014-10-09 01:40:46
【问题描述】:
我目前有一个使用 Storyboard 的 Xcode 项目。在我的 AppDelegate 中,我需要设置一些包含在其他视图控制器的 .h 文件中的属性,以响应应用收到的通知。
如何在 AppDelegate 中实例化这些视图控制器的对象,以便我可以访问和修改它们的属性?
【问题讨论】:
标签: ios objective-c appdelegate
我目前有一个使用 Storyboard 的 Xcode 项目。在我的 AppDelegate 中,我需要设置一些包含在其他视图控制器的 .h 文件中的属性,以响应应用收到的通知。
如何在 AppDelegate 中实例化这些视图控制器的对象,以便我可以访问和修改它们的属性?
【问题讨论】:
标签: ios objective-c appdelegate
有一些方法可以让应用程序代理获取正确 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"];
}
【讨论】: