- Retaining and Releasing
- Assigning to Instance Variables
- Automatic Reference Counting
- Returning Objects via Pointer Arguments
- Avoiding Retain Cycles
- Migrating to ARC
- Autorelease Pools
- Using Autoreleased Constructors
- Autoreleasing Objects in Accessors
- Supporting Automatic Garbage Collection
- Interoperating with C
- Understanding Object Destruction
- Using Weak References
- Allocating Scanned Memory
Allocating Scanned Memory
If you allocate memory with malloc(), it is invisible to the garbage collector. This is a problem if you want, for example, something like a C array containing objects. We’ve already looked at one solution to this. You can call CFRetain() on the object you are about to store and CFRelease() on the old value, and then swap them over.
This is not ideal, although it will work. The other option is to allocate a region of memory from the garbage collector. The NSAllocateCollectable() function is similar to malloc(), but with two important differences.
The first is that the memory that it returns is garbage collected. There is no corresponding NSFreeCollectable() function. When the last pointer to the buffer disappears, the buffer will be collected.
The second difference is that the second parameter to this function defines the kind of memory that you want. If you are going to be using the buffer for storing C types, you can just pass zero here. If you pass NSScannedOption, the returned buffer will be scanned as a possible location of object pointers, as well as pointers to other memory regions returned by NSAllocateCollectable().