ios - Do I need to add observer if I have a func to take NSNotification as parameter -


just question title

for have code like

func receievenotification(notification : nsnotification) {      ......verify notification     ......retrieve userinfo  } 

do still need add observer nsnotificationcenter.defaultcenter() ? if do. how to?

an nsnotification sent when object calls post method on nsnotificationcenter. notification center calls designated receiving method on each object has been registered it.

if not register notification center, there no way system know should send notification you. although there can other registration centers, in ios use default.

when register notification, specify object receive notification, method on object call, notification registering for, , sender want receive notifications from. if want receive every 1 of particular kind of notification (that is, don't care object sent it), can specify nil sender.

thus, register notification, "mynotification", , don't care object sent it, call following:

nsnotificationcenter.defaultcenter().addobserver(self, "gesturehandler", "mynotification", nil) 

where place call depends on when want object listen it. example, if receiver uiview, want register when view shown, not when view created.

it extremely important unregister when want stop receiving notifications, such when receiver goes out of scope. calling 'removeobserver()`.

you should search through xcode's documentation , read notification programming topics.


Comments