Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Supporting Automatic Garbage Collection

Starting with OS X 10.5, Apple introduced automatic garbage collection to Objective-C. This can make life easier for programmers, but in most cases it comes with a performance penalty. Apple’s collector uses a lot of memory to track live references and therefore is not available on the iPhone. It is also not supported with older versions of OS X and has only limited support with GNUstep, so you should avoid using garbage collection if you want to write portable code.

If you compile your code in garbage collected mode, all -retain, -release, and -autorelease messages will be ignored. The compiler will automatically insert calls to functions in the runtime for every assign operation to memory on the heap.

Code must be compiled with garbage collection support to use the garbage collector. This will insert calls to a set of functions that, on the Mac runtime, are declared in objc-auto.h on any assignment to memory on the heap.

These functions make sure that the garbage collector is aware of the write. These are required because the collector is concurrent. It will run in a background thread and will delete objects when it can no longer find references to them. The collector must be notified of updated pointers, or it might accidentally delete an object that you have just created a reference to.

You have two options when compiling for garbage collection. If you compile with the -fobjc-gc-only flag your code will only support garbage collection. If you compile with the -fobjc-gc flag, the code will support both reference counting and automatic garbage collection. This is useful when you are compiling a framework. You must still remember to add -retain and -release calls in the correct places, but users of your framework can then use it with or without collection.

From: objc-auto.h

  • + Share This
  • 🔖 Save To Your Account