iOS - Why my next view callback my previous view?

72 Views Asked by At

My situation is the next :
I have two view controller. The first contains an UITableView. When I tap on a cell, the second view is called and display another UITableView.

Problem :
Immediately that my second view has been displayed, it's removed and my app come back on the first view.

In debug mode, I can see that viewDidLoad() is called and the TableView has been initialised because the TableView is filled.

But I don't know why, viewWillDisappear() is called immediately, as if the view was removed...

Could someone to help me out please?

EDIT :

My first View :

#import "CIMSaddlesResearchesSavedViewController.h"
#import <Foundation/Foundation.h>

@interface CIMSaddlesResearchesSavedViewController ()

@property (weak, nonatomic) IBOutlet UITableView    *tableView;

@end

@implementation CIMSaddlesResearchesSavedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"NavigationBarBackground"] forBarMetrics:UIBarMetricsDefault];
}

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}

- (UIStatusBarStyle) preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.researches count];
}

- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    static NSString     *reuseIdentifier    = @"researchCell";
    UITableViewCell     *cell               = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    CIMSaddleResearch   *research;
    
    research = self.researches[indexPath.row];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"researchCell"];
    }
    
    cell.textLabel.textColor        = [UIColor whiteColor];
    cell.detailTextLabel.textColor  = [UIColor whiteColor];
    cell.backgroundColor            = [UIColor clearColor];
    
    if (research.dbId && ![research.dbId isEqual:@""]) {
        CIMDbManager    *dbMngr     = [[CIMDbManager alloc] init];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"dd/MM/yyyy"];
        NSMutableString *minPrice    = [NSMutableString stringWithString:@""];
        NSMutableString *maxPrice    = [NSMutableString stringWithString:@""];
        NSMutableString *currencyS   = [NSMutableString stringWithString:@""];
        CIMCurrency *currency = [[CIMCurrency alloc] init];;
        
        NSMutableString *researchText         = [NSMutableString stringWithString:@""];
        
        if (research.customer && ![research.customer isEqual:@""]) {
            CIMCustomer     *customer   = [[CIMCustomer alloc] init];
            customer.dbId               = research.customer;
            customer                    = [dbMngr firstObjectFromDb:customer];
            [researchText appendFormat:@"%@ le %@", customer.lastName, [formatter stringFromDate:research.date]];
        }
        
        CIMSaddleResearchLine *researchLine = [[CIMSaddleResearchLine alloc] init];
        researchLine.saddleResearch = research.dbId;
        NSArray *lines = [dbMngr objectsFromDb:researchLine];
        
        for(CIMSaddleResearchLine *line in lines){
            if([line.field isEqualToString:@"PRIX_MIN"])
               [minPrice appendFormat:@"%@", line.value];
            else if([line.field isEqualToString:@"PRIX_MAX"])
                [maxPrice appendFormat:@"%@", line.value];
            else if([line.field isEqualToString:@"DEVISE"])
                [currencyS appendFormat:@"%@", line.value];
        }
        
        if(![minPrice isEqual:@""] || ![maxPrice isEqual:@""]){
            if(currencyS){
                currency.dbId = currencyS;
                currency = [dbMngr firstObjectFromDb:currency];
            } else {
                currency = [dbMngr defaultSocietyCurrency];
            }
            
            [researchText appendString:@" | Budget : "];
            if(![minPrice isEqual:@""] && ![maxPrice isEqual:@""])
                [researchText appendFormat:@"%@%@ → %@%@", minPrice, currency.symbol, maxPrice, currency.symbol];
            else if(![minPrice isEqual:@""] && [maxPrice isEqual:@""])
                [researchText appendFormat:@"%@%@ min.", minPrice, currency.symbol];
            else if([minPrice isEqual:@""] && ![maxPrice isEqual:@""])
                [researchText appendFormat:@"%@%@ max.", maxPrice, currency.symbol];
        }
        
        NSMutableString *researchDetailText   = [NSMutableString stringWithFormat:@"Relance le : %@", [formatter stringFromDate:research.deadline]];
        
        CIMResearchStatus *status = [[CIMResearchStatus alloc] init];
        status.dbId              = research.status;
        status                   = [dbMngr firstObjectFromDb:status];
        
        if(status){
            [researchDetailText appendFormat:@" (%@)", status.name];
        }
        
        cell.textLabel.text         = researchText;
        cell.detailTextLabel.text   = researchDetailText;
        
        if (research.comment && ![research.comment isEqual:@""] ) {
            cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
        }
    } else {
        cell                            = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"saddleCell"];
        cell.backgroundColor            = [UIColor clearColor];
        cell.textLabel.text             = NSLocalizedString(@"The saddle is not in this list", nil);
        cell.textLabel.textAlignment    = NSTextAlignmentCenter;
    }
    
    return cell;
}

-(void) tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    CIMSaddleResearch *research = self.researches[indexPath.row];
    
    if (research.comment && ![research.comment isEqual:@""] ) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Comment", nil)
                                                                       message:research.comment
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:NSLocalizedString(@"Ok", nil)
                                                           style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction *action){}];
        
        [alert addAction:actionOk];
        [self presentViewController:alert animated:YES completion:nil];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.navigationController popViewControllerAnimated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"openResultResearch"]) {
        UITableView                         *table          = (UITableView*)[(UITableViewCell*)sender superview];
        NSIndexPath                         *index          = [table indexPathForCell:(UITableViewCell*) sender];
        CIMSaddleResearch                   *research       = self.researches[index.row];
        
        CIMDbManager                        *dbMngr         = [[CIMDbManager alloc] init];
        CIMSaddleResearchLine               *researchLine   = [[CIMSaddleResearchLine alloc] init];
        CIMSaddleResearchFormViewController *form           = [[CIMSaddleResearchFormViewController alloc] init];
        form.minimumPriceRow                                = [[XLFormRowDescriptor alloc] init];
        form.maximumPriceRow                                = [[XLFormRowDescriptor alloc] init];
        form.minimumYearRow                                 = [[XLFormRowDescriptor alloc] init];
        form.maximumYearRow                                 = [[XLFormRowDescriptor alloc] init];
        form.currency                                       = [[CIMCurrency alloc] init];
        
        NSMutableDictionary                 *filters        = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                                                   [[NSMutableArray alloc] init], @"brand",
                                                                   [[NSMutableArray alloc] init], @"model",
                                                                   [[NSMutableArray alloc] init], @"size",
                                                                   [[NSMutableArray alloc] init], @"color",
                                                                   [[NSMutableArray alloc] init], @"finishing",
                                                                   nil];
        
        researchLine.saddleResearch = research.dbId;
        NSArray *lines = [dbMngr objectsFromDb:researchLine];
        NSSortDescriptor    *sortFieldDesc           = [[NSSortDescriptor alloc] initWithKey:@"field" ascending:YES selector:@selector(compare:)];
        NSSortDescriptor    *sortOrderDesc           = [[NSSortDescriptor alloc] initWithKey:@"order" ascending:YES selector:@selector(compare:)];
        lines = [lines sortedArrayUsingDescriptors:@[sortFieldDesc, sortOrderDesc]];
        
        for(CIMSaddleResearchLine *line in lines){
            if([line.field isEqualToString:@"PRIX_MIN"]){
                form.minimumPriceRow.value = line.value;
            }else if([line.field isEqualToString:@"PRIX_MAX"]){
                form.maximumPriceRow.value = line.value;
            }else if([line.field isEqualToString:@"ANNEE_MIN"]){
                form.minimumYearRow.value = line.value;
            }else if([line.field isEqualToString:@"ANNEE_MAX"]){
                form.maximumYearRow.value = line.value;
            }else if([line.field isEqualToString:@"DEVISE"]){
                form.currency.dbId = line.value;
                form.currency = [dbMngr firstObjectFromDb:form.currency];
            }
            else if([line.field isEqualToString:@"GA_REFCONSTRUC"]){
                form.serialNumberRow.value = line.value;
            }else if([line.field isEqualToString:@"GA_QUARTIER"]){
                form.flapRow.value = line.value;
            }else if([line.field isEqualToString:@"GA_MARQUE"]){
                CIMBrand *brand = [[CIMBrand alloc] init];
                brand.dbId      = line.value;
                [[filters objectForKey:@"brand"] addObject:[dbMngr firstObjectFromDb:brand]];
            }else if([line.field isEqualToString:@"GA_MODEL"]){
                CIMModel *model = [[CIMModel alloc] init];
                model.dbId      = line.value;
                [[filters objectForKey:@"model"] addObject:[dbMngr firstObjectFromDb:model]];
            }else if([line.field isEqualToString:@"GA_TAILLE"]){
                CIMSize *size = [[CIMSize alloc] init];
                size.dbId      = line.value;
                [[filters objectForKey:@"size"] addObject:[dbMngr firstObjectFromDb:size]];
            }else if([line.field isEqualToString:@"GA_COULEUR"]){
                CIMColor *color = [[CIMColor alloc] init];
                color.dbId      = line.value;
                [[filters objectForKey:@"color"] addObject:[dbMngr firstObjectFromDb:color]];
            }else if([line.field isEqualToString:@"GA_FINITION"]){
                CIMFinishing *finishing = [[CIMFinishing alloc] init];
                finishing.dbId      = line.value;
                [[filters objectForKey:@"finishing"] addObject:[dbMngr firstObjectFromDb:finishing]];
            }
        }
        
        if(!form.currency.dbId && [form.currency.dbId isEqualToString:@""]){
            CIMCustomer *customer = [[CIMCustomer alloc] init];
            customer.dbId = research.customer;
            customer = [dbMngr firstObjectFromDb:customer];
            form.currency.dbId = customer.currency;
            form.currency = [dbMngr firstObjectFromDb:form.currency];
        }
        
        CIMSaddlesViewController    *saddlesViewController  = segue.destinationViewController;
        saddlesViewController.filters                       = filters;
        saddlesViewController.saddleDbId                    = [NSMutableString stringWithString:@""];
        saddlesViewController.selectionMode                 = NO;
        saddlesViewController.saddleNotFoundOption          = NO;
        saddlesViewController.showSaddlePictures            = YES;
        saddlesViewController.showSaddleWarehouse           = YES;
        saddlesViewController.showToolbar                   = NO;
        saddlesViewController.saddles                       = [dbMngr stockSaddlesWithFilters:filters
                                                                              andSerialNumber:form.serialNumberRow.value
                                                                                      andFlap:form.flapRow.value
                                                                          betweenMinimumPrice:form.minimumPriceRow.value
                                                                              andMaximumPrice:form.maximumPriceRow.value
                                                                                   inCurrency:form.currency.dbId
                                                                           betweenMinimumYear:form.minimumYearRow.value
                                                                               andMaximumYear:form.maximumYearRow.value
                                                                                      inStock:YES];
        saddlesViewController.formResearch                  = form;
        saddlesViewController.saddlesPricesCurrency         = form.currency;
    }
}
@end

My second view :

#import "CIMSaddlesViewController.h"

@interface CIMSaddlesViewController ()

@property (weak, nonatomic) IBOutlet UITableView    *tableView;

@end

@implementation CIMSaddlesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"NavigationBarBackground"] forBarMetrics:UIBarMetricsDefault];
}

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}

- (UIStatusBarStyle) preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.saddles count];
}

- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    static NSString *reuseIdentifier    = @"saddleCell";
    UITableViewCell *cell               = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    CIMItem         *saddle;
    
    saddle = self.saddles[indexPath.row];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"saddleCell"];
    }
    
    cell.textLabel.textColor        = [UIColor whiteColor];
    cell.detailTextLabel.textColor  = [UIColor whiteColor];
    cell.backgroundColor            = [UIColor clearColor];
    
    if (saddle.dbId && ![saddle.dbId isEqual:@""]) {
        NSMutableString *saddleText         = [NSMutableString stringWithString:saddle.dbId];
        NSMutableString *saddleDetailText   = [NSMutableString stringWithString:saddle.name];
        
        // Serial number
        if (saddle.serialNumber && ![saddle.serialNumber isEqual:@""]) {
            [saddleText appendFormat:@" - %@", saddle.serialNumber];
        }
        
        // Warehouse
        if (self.showSaddleWarehouse) {
            CIMDbManager    *dbMngr = [[CIMDbManager alloc] init];
            CIMStock        *stock  = [[CIMStock alloc] init];
            stock.item              = saddle.dbId;
            stock.quantity          = [NSNumber numberWithInt:1];
            stock                   = [dbMngr firstObjectFromDb:stock];
            if (stock) {
                CIMWarehouse *warehouse = [[CIMWarehouse alloc] init];
                warehouse.dbId          = stock.warehouse;
                warehouse               = [dbMngr firstObjectFromDb:warehouse];
                [saddleText appendFormat:@" → [%@]", warehouse.name];
            }
        }
        
        // Estimed price
        if (self.saddlesPricesCurrency) {
            CIMDbManager    *dbMngr         = [[CIMDbManager alloc] init];
            CIMSaddlePrices *saddlePrices   = [[CIMSaddlePrices alloc] init];
            saddlePrices.item               = saddle.dbId;
            saddlePrices.currency           = self.saddlesPricesCurrency.dbId;
            saddlePrices                    = [dbMngr firstObjectFromDb:saddlePrices];
            if (saddlePrices) {
                NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
                [numberFormatter setMaximumFractionDigits:0];
                [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
                [numberFormatter setCurrencyCode:self.saddlesPricesCurrency.isoCode];
                
                NSString *isEstimateStr;
                if ([saddlePrices.isEstimate isEqual:@"-"]) {
                    isEstimateStr = NSLocalizedString(@"Official price", nil);
                } else {
                    isEstimateStr = NSLocalizedString(@"Estimation", nil); 
                }
                
                [saddleText appendFormat:@" | %@ (%@)", [numberFormatter stringFromNumber:saddlePrices.price], isEstimateStr];
            }
        }
        
        cell.textLabel.text         = saddleText;
        cell.detailTextLabel.text   = saddleDetailText;
        
        // Saddle pictures
        if (self.showSaddlePictures && [[self.saddlesPicturesDictionary allKeys] containsObject:saddle.dbId]) {
            UIButton *accessoryButton       = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 40.0f, 40.0f)];
            if ([self.saddlesiPadPictures containsObject:saddle.dbId]) {
                [accessoryButton setImage:[UIImage imageNamed:@"SaddleiPadPictureButton"] forState:UIControlStateNormal];
            } else {
                [accessoryButton setImage:[UIImage imageNamed:@"SaddlePictureButton"] forState:UIControlStateNormal];
            }
            accessoryButton.tag             = indexPath.row;
            [accessoryButton addTarget:self action:@selector(showSaddlePicturesViewForSaddleWithSender:) forControlEvents:UIControlEventTouchDown];
            cell.accessoryView              = accessoryButton;
        } else {
            cell.accessoryView              = nil;
        }
    } else {
        cell                            = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"saddleCell"];
        cell.backgroundColor            = [UIColor whiteColor];
        cell.textLabel.text             = NSLocalizedString(@"The saddle is not in this list", nil);
        cell.textLabel.textAlignment    = NSTextAlignmentCenter;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.selectionMode) {
        CIMItem *saddle = self.saddles[indexPath.row];
        [self.saddleDbId setString:saddle.dbId];
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}
@end

To be honest, this project is very big, I begun to work on it since 2 month ago and I'm alone to work on it. I didn't work in Objective-C before and even less with X-Code. I'm discovering features and Objective-C gradually...

1

There are 1 best solutions below

2
On BEST ANSWER

In your first VC you call [self.navigationController popViewControllerAnimated:YES]; which tells the navigationVC to pop the currently visible view controller. If you set breakpoints to the tableview didSelectRowAtIndexPath: in first VC and to viewDidLoad in your second VC you'll see in what order they are called. I have a feeling that the order of execution could be the following:

  1. prepare for segue in firstVC
  2. view did load in secondVC
  3. didSelectRowAtIndexPath in first VC
  4. finally your second VC unloads

This is my idea without testing it. Please make sure you really need to pop the VC in didSelectRow