1

I have lots of methods like this:

-(NSObject *)theObject
{
    static NSObject *obj = nil;
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        obj = [[NSObject alloc] init];
        atexit_b (^{
            [obj release], obj = nil;
        });
    });
    return obj;
}

I think the original purpose of using atexit_b was to be a good citizen and release the memory used just before the application ends :). However, AFAIK, the runtime will re-collect all memory when my application exits (or terminated, etc) anyway.

Can I always assume this? or perhaps it depends on the OS/runtime/some implementation?

In my particular case, I have several (lets say a few dozens) of atexit_b calls all around the application, so it means some amount of memory is being used to do something unneeded.

Is this true? If so, then does it mean I don't need atexit_b calls?

nacho4d
  • 43,720
  • 45
  • 157
  • 240

1 Answers1

1

There are - as far as I can see - two major reasons to use atexit_b();

  • You need to clean up/sync resources that don't necessarily can be just terminated. As an "extreme" example, if you're controlling a robot, you may want to force it to stop moving before terminating the program. A word processor may want to ensure that the saved file is in a consistent state. Of course, there are probably other ways to achieve this that would be safer.

  • You need cleanup of semi independent resources to be executed in a specific order. atexit_b() cleans up in the reverse order things were registered, so if you need the stepper motor to park the hard disk head before the spinner motor is powered off, you could use it.

In your case, it should be just as safe to remove, unless another cleanup method counts on theObject returning null during cleanup.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294