Question

I´ve got a question based on the NSNotification in Objective-C:

[[NSNotificationCenter defaultCenter] addObserver:self 
                                      selector:@selector(method:)
                                      name:@"SOME_STRING"
                                      object:nil];

I really don´t know how to set the object attribute...

So, if I only want to recieve notifications from class a, how can I set it to class a?

[A class]

and

[A alloc]

dosen´t work.

I´m very confused about the object parameter.

Was it helpful?

Solution

if nil, then you get all @"SOME_STRING" notifications sent.

if not nil, you get only those which pertain to the instance passed to object.

so... it's not really an association "from class a", it's an association to a specific instance. when the instances match (observe and post), you are notified.

With that information, you could use the objc instance returned by [A class] as the object parameter in order to receive the notifications you are interested in -- it looks like this:

Observe:

[[NSNotificationCenter defaultCenter] addObserver:self 
                                      selector:@selector(method:)
                                      name:@"SOME_STRING"
                                      object:[A class]];
                                              ^^^^^^^

Post:

[[NSNotificationCenter defaultCenter]
  postNotificationName:@"SOME_STRING" object:[A class]];
                                              ^^^^^^^

OTHER TIPS

The object parameter is the object you want to observe, you can't observe a class.

But in your method you can check object class:

[[NSNotificationCenter defaultCenter] addObserver:self 
                                      selector:@selector(method:)
                                      name:@"SOME_STRING"
                                      object:nil];

- (void)method:(NSNotification*)notif
{
    if ([[notif object] isKindOfClass:[A class]]) {
        //...
    }
}

For Post a Notification you can use below method :-

[[NSNotificationCenter defaultCenter] postNotificationName:@"testNotification" object:[A class]];

To Receive a Notification first add below method in your viewDidLoad method :-

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyWhenCalled:) name:@"testNotification" object:[A class]];

Declare below selector. This will called when your notification is fired :-

- (void) notifyWhenCalled:(NSNotification *)notification
{
  if ([[notification object] isKindOfClass:[A class]]) 
  {
    //..... Write your code to do anything.
  }
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top