Release the ViewController correctly when adding a subview without a navigationController

Something that I encounter in many cases cannot correctly create and destroy ViewController when adding ViewController.view as a subobject not on the navigation controller.

eg:

MyViewController *myViewController = [[MyViewController alloc] init];  
[currentView addSubView:myViewController.view];  
[myViewController release];

This works great if it is an uncontrolled view and there are no UIControls that the user needs to interact with. But sending messages to the view controller of this kind causes EXEC_BAD_ACCESS , since they are no longer in memory.

MyViewController *myViewController = [[MyViewController alloc] init];  
[currentView addSubView:myViewController.view]; 

This works when sending messages, however it is a memory leak and is caught by the static analyzer.

. MyViewControllers - UIScrollView, .

for (int i = 0; i < [myViewControllers count]; i++) {  
    MyViewController *myTmpViewController = [[MyViewController alloc] init];
    [myCurrentUIScrollView addSubview:myTmpViewController.view];
    [myTmpViewController release];
}

- , myTmpViewController - . ?

+3
3

NSMutableArray .


for (int i = 0; i < [myViewControllers count]; i++) {  
    MyViewController *myTmpViewController = [[MyViewController alloc] init];
    [myCurrentUIScrollView addSubview:myTmpViewController.view];
    [myControllers addObject:myTmpViewController];
    [myTmpViewController release];
}

// ..

- (void) dealloc {
    [super dealloc];
    [myControllers release];
}

+1

ivar, dealloc .

+1

" ", UIView (, )

Otherwise, you need to decide for the most logical "owner" of these view controllers (often the viewcontroller parentview) and make them ivars their owner.

0
source

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


All Articles