我目前有一個Xcode項目,我正在使用故事板。在我的AppDelegate中,我需要設置一些包含在其他視圖控制器的.h文件中的屬性,以響應應用程序收到的通知。從AppDelegate訪問視圖控制器的屬性
如何在AppDelegate中實例化這些視圖控制器的對象,以便我可以訪問和修改它們的屬性?
我目前有一個Xcode項目,我正在使用故事板。在我的AppDelegate中,我需要設置一些包含在其他視圖控制器的.h文件中的屬性,以響應應用程序收到的通知。從AppDelegate訪問視圖控制器的屬性
如何在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"];
}
我真的不知道如何使用NSNotificationCenter。我將如何添加觀察者?另外,對象的指針可以存儲在字典中嗎? – Satre 2014-10-09 02:04:26
@Satre - 詳細編輯 – danh 2014-10-09 02:17:01
感謝您的解釋。 對於observedHi方法,我注意到你沒有傳入通知參數,儘管它的聲明中有一個。 NSNotificationCenter默認會這樣做嗎? – Satre 2014-10-09 02:30:11