您可以在 中发布通知ClassA,并在其他类(即)中注册该通知。ClassB
您可以这样做:
(在ClassA):
[[NSNotificationCenter defaultCenter]
postNotificationName:@"noteName" object:self];
(在ClassB):
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(doSomething:)
name:@"noteName" object:nil];
每当一个实例ClassA发布一个新通知时,将通知已注册到该通知的其他实例(即时)。在这种情况下,ClassB将执行doSomething:(NSNotification *)note.
[编辑]
您可以将该通知发布到您的 setter 方法 ( setVar:(NSString*)newVar)。
如果你想传递一些东西,请使用postNotificationName:object:userInfo:变体。userInfo是 a NSDictionary,你可以在其中传递任何你想要的东西。例如:
NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:var, @"variable", nil];
[[NSNotificationCenter defaultCenter]
postNotificationName:@"noteName" object:self userInfo:dic];
现在,编辑您的doSomething:方法:
-(void)doSomething:(NSNotification*)note {
if ([[note name] isEqualToString:@"noteName"]) {
NSLog(@"%@", [note userInfo]);
}
}
更多信息:
https ://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Notifications/Introduction/introNotifications.html
https://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/Notification.html
https://developer.apple.com/library/mac/#documentation/Darwin/Conceptual/MacOSXNotifcationOv/Introduction/Introduction.html