Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under Automatic Reference Counting (ARC), where do I put my free() statements?

In cocoa, ARC frees you of having to worry about retain, release, autorelease, etc. It also prohibits calling [super dealloc]. A -(void) dealloc method is allowed, but I'm not sure if/when it's called.

I get how this is all great for objects, etc., but where do I put the free() that matches the malloc() I did in -(id) init ?

Example:

@implementation SomeObject

- (id) initWithSize: (Vertex3Di) theSize
{
    self = [super init];
    if (self)
    {
        size = theSize;
        filled = malloc(size.x * size.y * size.z);
        if (filled == nil)
        {
            //* TODO: handle error
            self = nil;
        }
    }

    return self;
}


- (void) dealloc         // does this ever get called?  If so, at the normal time, like I expect?
{
    if (filled)
        free(filled);    // is this the right way to do this?
    // [super dealloc];  // This is certainly not allowed in ARC!
}
like image 781
Olie Avatar asked Nov 30 '22 03:11

Olie


1 Answers

You are right, you have to implement dealloc and call free inside of it. dealloc will be called when the object is deallocated as before ARC. Also, you can't call [super dealloc]; as this will be done automatically.

Finally, note that you can use NSData to allocate the memory for filled:

self.filledData = [NSMutableData dataWithLength:size.x * size.y * size.z];
self.filled = [self.filledData mutableBytes];

When you do this, you don't have to explicitly free the memory as it will be done automatically when the object and consequently filledData are deallocated.

like image 149
sch Avatar answered Dec 21 '22 05:12

sch