Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

A coding pattern that does not work under Garbage Collection




I've been testing some of our older libraries under GC, and have found one coding pattern (that may well have been bad practice anyway) that really does not work well under GC.


I used to use convenience constructors for NSMutableData objects as a kind of lazy replacement for malloc.

That is, an assignment like this:

float *myPointer = [[NSMutableData dataWithLength:size*sizeof(float)] mutableBytes]; // Memory freed at end of event loop

could be used in place of

float *myPointer = (float*)malloc(size*sizeof(float)); // Needs a free() later

The advantage of the first, under traditional memory management, was that the memory would presumably be cleaned up at the end of the current event loop (whereas the second would require a malloc downstream in the code).

It seems like this (not surprisingly) doesn't work reliably under GC, as the collector obviously has no way of knowing that you are later looking at the memory originally addressed by myPointer. It keeps track of objects and not pointers.

One possible solution is to replace the first assignment with

NSMutableData *myData = [NSMutableData dataWithLength:size*sizeof(float)];

and use

 ((float*)[myData mutableBytes])  in place of myPointer.

The other option is to just use malloc/free pairs - which I don't mind to a certain extent but the autoreleased convenience constructor was nice when there were a lot of little chunks of data to allocate which would not be needed after the end of the event loop. I guess the concept of a convenience constructor no longer has the same significance it did pre-GC.

As there are probably better ways of approaching this kind of situation, I'd be interested in any suggestions or comments. The way I was doing it before was probably just bad... still this explained a few spooky bugs in one of our apps under GC.

Cheers,

Rick
_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/email@hidden

This email sent to email@hidden


Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.