4

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!
}
sch
  • 27,436
  • 3
  • 68
  • 83
Olie
  • 24,597
  • 18
  • 99
  • 131
  • 2
    `free(0)` is a no-op, so `free(filled)` is a simpler way to write `if (filled) free(filled);`. (I see another poster wrote this below, but it's not in the accepted answer so I thought I'd leave it here, too.) – paulmelnikow Mar 13 '12 at 20:27

2 Answers2

14

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.

sch
  • 27,436
  • 3
  • 68
  • 83
8

Yes, you put it in -dealloc just like you do under MRR. The only difference with -dealloc is you must not call [super dealloc]. Other than that, it's exactly the same, and will get called when the object is fully released.


As an aside, free() will accept the NULL pointer and do nothing, so you don't actually need that conditional in -dealloc. You could just say

- (void)dealloc {
    free(filled);
}
Lily Ballard
  • 182,031
  • 33
  • 381
  • 347