Under automatic link counting (ARC), where can I put my free () statements?

In cocoa, ARC frees you from having to worry about saving, releasing, auto-advertising, etc. It also prohibits calling [super dealloc] . The allowed method -(void) dealloc , but I'm not sure when / when it is called.

I understand how all of this is great for objects, etc., but where do I put free() , which matches malloc() , which 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! } 
+4
source share
2 answers

You are right, you need to implement dealloc and call free inside it. dealloc will be called when the object is released as ARC. In addition, you cannot call [super dealloc]; as this will be done automatically.

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

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

When you do this, you do not need to explicitly free the memory, as this will be done automatically when the object and, therefore, filledData are freed.

+14
source

Yes, you put it in -dealloc just like you did in MRR. The only difference from -dealloc is that you should not call [super dealloc] . In addition, it is exactly the same and will be called when the object is fully released.


Aside, free() will accept a NULL pointer and do nothing, so you really don't need this condition in -dealloc . Could you just say

 - (void)dealloc { free(filled); } 
+8
source

Source: https://habr.com/ru/post/1401237/


All Articles