這與Naresh的回答非常相似,因爲所有來自NSNotificationCenter
的通知都以相同的方式工作。
基本上,您將選擇通知的名稱(例如:@"NOTIFICACION_NAME"
),然後您需要接收該事件的每個對象都將訂閱具有該名稱的所有通知。
所以,在你的應用程序代理,你將發佈(例如,「廣播」)這個名字的通知:
-(BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
// First, create a dictionary with all the data needed to pass.
NSDictionary *notificationInfo = @{
@"url" : url,
@"sourceApplication" : sourceApplication,
@"annotation" : annotation
};
// Post the notification to all objects that listen to it.
[[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATION_NAME"
object:self
userInfo:notificationInfo];
}
現在,我們需要趕在你需要它的其他文件通知。所以:
- (instancetype)init {
self = [super init];
if (self) {
// Subscribe to the notifications called "NOTIFICATION_NAME"
// The "object" parameter is nil so we get notification from all objects that post that particular notification name.
// It could also be [[UIApplication sharedApplication] delegate] to receive notifications only from the app delegate.
// If you process the event in a UIViewController, do this in viewDidLoad instead of init.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(openedWithURLScheme:)
name:@"NOTIFICATION_NAME"
object:nil];
}
}
- (void)dealloc {
// Unsubscribe from all notifications at dealloc time. If you don't do this,
// your app will crash when the app delegate posts the notifications
// after this particular object was deallocated.
// If it's a UIViewController, do this in viewDidUnload.
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)openedWithURLScheme:(NSNotification *)notification {
// The notification was received, so this method is called with the
// notification object as a parameter. Now we get the dictionary
// we sent with all the info.
NSDictionary *notificationInfo = notification.userInfo;
// Now get the data you need:
NSURL *url = notificationInfo[@"url"];
NSString *sourceApplication = notificationInfo[@"sourceApplication"];
id annotation = notificationInfo[@"annotation"];
// Do what you need with that info...
}
在簡單的話:當你的應用程序代理接收到特定的方法,我們廣播接收到的「聽」(觀察)特定的通知每一個對象(通知)的信息。應該使用NSDictionary
完成。
欲瞭解更多信息,請閱讀official documentation at Apple website。
這是不是很清楚你想要什麼。你能解釋一下嗎? –
當我打開我的應用程序使用URL計劃這個函數被調用。但只有在我的AppDelegate.m文件中才有效。我想使它在同一目錄中的另一個文件中工作。 –
啊,你有幾個選擇。例如,您可以使用自定義類定義委託對象。你有沒有嘗試使用'NSNotificationCenter'的通知?我相信這是一個更好的選擇。 –