Maik639 Maik639 - 1 year ago 135
iOS Question

iOS / Objective-C: NSNotification

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.

Answer Source

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]];
                                              ^^^^^^^
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download