Object highlighted by application delegate displayed in multiple subheadings?

I have a little pickle here. Create an iOS game that contains two views: BaseView and MapView. Now they, of course, have the same appDelegate.

In both cases, a subclass of UIView called rivbox is used . In previous builds, I highlighted an rivbox instance in both Base and Map-view. When I realized that I would have many subheadings using this rivbox, I decided instead to select only one instance of rivbox in appDelegate, and then when the preview is loaded, I can "borrow" rivbox from appDelegate using these great features.

-(void)viewDidLoad { //Get all the sweets from the parent! appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; rivbox = appDelegate.rivbox; [self.view addSubview:rivbox]; ... } 

And this function is intended to update the owner, if we return to this view again

 -(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; if(rivbox != nil) { [rivbox setDelegate:self]; [self.view addSubview:rivbox]; } } 

It's fine! I find rivbox in appDelegate and it is updated! When I switch to another view, it loads there too just fine! But when I return to the first view, it seems to be a leak?!?! I do not see rivbox in my previous view when I return to it, although the previous view now belongs to it!

Problem: what's wrong with this? Should I really add rivbox as a subview every time I return to an already loaded view? If I delete this line, I cannot see MyBox when I return to the previous view.

0
source share
2 answers

This is really bad practice. If you mean the application delegate in any class, you probably need to rethink what you are doing.

From Apple Docs :

An application delegate is a custom object created during application startup, usually using the UIApplicationMain function. The main task of this object is to handle state transitions in the application. For example, this object is responsible for initializing and processing startup triggers.

Calling the application delegate for something else is like using global variables. This seems like an easy cut in the beginning, but can quickly end in a confusing mess as your code base grows.

The application delegate is what it says - the UIApplication delegate object. The views you create have nothing to do with UIApplication, so there should not be a delegate next to it.

Create and create simple, self-contained classes that encourage reuse. In the long run, you will be glad you did.

What advantage do you feel when creating this single rivbox ?

+2
source

This should be sufficient for both controllers:

 - (void)viewWillAppear:(BOOL)animated { //Get all the sweets from the parent! appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; [self.view addSubview:appDelegate.rivbox]; ... } 
0
source

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


All Articles