tags:

views:

69

answers:

3

Hi All,

I would like to add notification center from a cpp class, is it possible???? if Yes how to do it. Manager.h

class Manager
{

  Manager();

};

Manger.mm file

Manager:Manager()
{
[[NSNotificationCenter dafaultCenter] addObserver:self selector:@selector(workermethod) name:@" Name" object:(id)nil];
}

My compiler gives an error saying self is not declared.......ya i knw its an obvious error.since im not deriving from NSObject.... Please let me knw if its possible to add notification center to cpp class in cocoa??

+4  A: 

No, you can't do that.

The Objective-C and C++ class hierarchies are separate. In a C++ context, self is not defined but this is defined. In an Objective-C context, this is not defined and self is.

Also, addObserver takes an id parameter. C++ object instances are not considered of type id so even if you change your code to pass this instead of self it won't compile.

See the C++ Limitations from the Objective-C Programming Language Manual.

As a workaround, create an Objectve-C class which has an instance of the C++ object you want the notification to go to, and simply call the C++ method on it when the Objective-C object gets the notification.

Ben S
Then can you suggest me any alternative....Its a big project..I cant change the cpp calling style to objective-c in all the classes.Im opting for notification center bcoz i cannot handle the thread synchronization using events in objetive-c.
Pradeep Kumar
Just added a workaround :)
Ben S
Not only are the class hierarchies separate, but even though C++ and Objective-C both have things called "objects" and "classes", they are completely different things in the two languages. It's like if somebody called started calling telegraphs "cellphones" — you still wouldn't be able to use a telegraph like a cellphone.
Chuck
A: 

As Ben S pointed out, you can't use a C++ object where an Objective-C object is expected. They're just not the same thing. If you're targeting 10.6, one alternative to making an Objective-C wrapper is to use NSNotificationCenter's addObserverForName:object:queue:usingBlock:. Just give it a block that calls a function on your object and you get the same effect as adding that object as an observer.

Just to emphasize, though, that is only possible on 10.6.

Chuck
A: 

Ya...Even i had the doubt it will not work.......but just wanted to confirm with the experts....Ben Thanks for the work around suggested.....

i need this application to suppot 10.3 as well... Thanks a lot.

Pradeep Kumar