[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Wrapping C functions

From: David Chisnall
Subject: Re: Wrapping C functions
Date: Thu, 6 Aug 2009 21:30:50 +0100

On 6 Aug 2009, at 20:56, Martin Kalbfuß wrote:

Thank you David. That helped a lot. I decided to have a global library object
created with load.

You don't need a global library object; put the initialisation in the +initialize method for a class that is responsible for creating the library context. Or put it in the -init method for a singleton object.

But how to release it? Currently I set an atexit function in the load method which calls the release method of the class. But is there an Objective-C

Why do you need to release it? If it's something that needs explicit cleanup then the user should release it. If you are using AppKit then you can register an observer for the notification that is sent before an app exists, but your other email indicated that you are just using Foundation. In this case, you should probably stick with atexit() if you really need cleanup.

Another point is that I want to forbid the instanciation of the class. I think a singleton is the right way to go. But how can I create a singleton,
when I cannot hide methods?

The traditional approach is to provide a +sharedInstance method and put in the documentation that people should call this instead. If you want, you can override +allocWithZone: to look a bit like this:

static id sharedInstance;
+ (void)initialize
        if (self == [YourClassName class])
                sharedInstance = [self new];
+ (id)allocWithZone: (NSZone*)aZone
        if (nil != sharedInstance)
                return sharedInstance;
        return [super allocWithZone: aZone];

This will allocate the shared instance when class receives the first message and return it whenever the class receives a +alloc message. It's not a very good solution; you also need to protect -init to make sure that someone who does alloc/init they are not reinitialising the object and clearing all of the ivars. Generally, just putting something in the documentation saying people should use +sharedInstance is enough.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]