2014-10-09 62 views
0

我目前有一个Xcode项目,我正在使用故事板。在我的AppDelegate中,我需要设置一些包含在其他视图控制器的.h文件中的属性,以响应应用程序收到的通知。从AppDelegate访问视图控制器的属性

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

回答

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"]; 
} 
+0

我真的不知道如何使用NSNotificationCenter。我将如何添加观察者?另外,对象的指针可以存储在字典中吗? – Satre 2014-10-09 02:04:26

+0

@Satre - 详细编辑 – danh 2014-10-09 02:17:01

+0

感谢您的解释。 对于observedHi方法,我注意到你没有传入通知参数,尽管它的声明中有一个。 NSNotificationCenter默认会这样做吗? – Satre 2014-10-09 02:30:11