Accessing Cocoa from Carbon from Cocoa
The title of this blog may take a little explaining.
I was looking to include a Carbon routine within my Cocoa application, but this routine needed to have access to both my instance variables and other Class methods. It is straight forward to use Cocoa commands in your Carbon routine, as long as they’re declared from within the routine itself. You have no access to the object reference “self”. This refers to the object in which your code resides.
In order to achieve this you first need to create an object of the Class method and an instance init method within your Class. Here I have a Class called AppController where my Carbon routine is located. I add the following code;
+ (AppController *) sharedController
{
return sharedController;
}
- (id) init
{
self = [super init];
sharedController = self;
// Any other initialiser code needed
return self;
}
Now from within my Carbon routine a new AppController ojbect class is created called controller. I can now use this controller object in place of “self”. This gives me access to all my instance variables and methods.
void MyCarbonRoutine
{
AppController *controller;
controller = [[AppController alloc] init];
[controller aCocoaRoutine];
// Any other coding needed here
[controller release];
}
Remember to release your controller object before leaving the Carbon routine or you could end up with all sort of problems.
- Thanks to Uli Kusterer for pointing out that they are Objects that are created and released and not the Classes themselves.
November 6th, 2007 at 8:24 pm
I had the same problem but followed Apples Spelling version. Took a while but it worked. This is so much easier. One thing I did need to do though was in the header file the +(AppController *) sharedController; needed to be + (id *) sharedController;, or it complains about a mismatch.