Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destroying objects on demand with ARC

What is the correct way to destroy an object with ARC?

I would like to destroy a number of UIViewControllers as well as an object holding an AUGraph at certain times during runtime.

At the moment, when my parent viewcontroller creates viewcontroller objects and assigns their views to its view, the objects obviously stay alive with the parent. I would like to destroy these child viewcontrollers the moment they are not needed.

like image 524
some_id Avatar asked Dec 05 '22 15:12

some_id


2 Answers

Just set the variables referencing those objects to nil. The compiler will then release the objects at that moment and they will be destroyed if no other strong references to them exist.

like image 121
Ole Begemann Avatar answered Dec 27 '22 11:12

Ole Begemann


ARC will insert a call to [release] when you set a __strong variable that references an object to nil.

@interface MyViewController : UIViewController {
    UIViewController *childViewController;
}
...

@end

-(void)destroyChild {
    childViewController = nil;
}

The same thing is done when you have a C-style array of objects: setting an element of your array to nil releases the item that was there unless it was __weak/__unsafe_unretained. If you keep child view controllers in an NSMutableArray, removing an object from the array decrements its reference count.

like image 38
Sergey Kalinichenko Avatar answered Dec 27 '22 10:12

Sergey Kalinichenko