Oscar Papel's Web Log

Thursday, November 11, 2004

Damocles from C to ObjC

Now that we have some memory managed "objects" in C with some functions that use them, we need to make real OO objects. Each ObjC object has a corresponding C "object".


@interface NSImage : NSObject {
Image *image;
}
- (id)init;
- (id)initWithImage:(Image *)pImage;
- (void)dealloc;
..... other messages ...
@end


When you allocate a NSImage object, with the init message, it allocates an underlying C "object". When the dealloc message is called, either through a release message or indirectly via a [NSAutoReleasePool release] message, the underlying C "object" is released. This way, ObjC object memory management works with C "objects" to make memory management seamless.

When you allocate a NSImage object with the initWithImage message, it performs an AddRef on the C "object". This way, it gets it's own reference to the C "object" which it can release in the same way that the first NSImage object does.

All these ObjC objects get compiled into a native Mac Framework and can be directly used by any Cocoa-based Mac project. This is how EyeImage (one of our commercial products) gets it's functionality.

There are some minor variations. For instance, an ObjC NSImage object might temporarily allocate a C Image "object" in order to generate a displayable image then immediately deallocate it. For performance reasons, no ObjC object wraps this temporary object. Such cases are rare, however. Premature optimization is the root of all software evil. In this case, however, the optimization was deemed worth it. This optimization does not cause a change in any software that uses NSImage. Optimization across an interface boundary is almost always an indication of bad design.

0 Comments:

Post a Comment

<< Home