iOS - Почему мой следующий просмотр обратного вызова моего предыдущего просмотра? - PullRequest
0 голосов
/ 28 мая 2018

Моя ситуация следующая:
У меня есть два контроллера вида.Первый содержит UITableView.Когда я нажимаю на ячейку, вызывается второй вид и отображается другое UITableView.

Проблема:
Сразу же после отображения моего второго представления оно удаляется, и мое приложение возвращается к первому виду.

В режиме отладки я вижу, что viewDidLoad() вызывается и TableView был инициализирован, потому что TableView заполнен.

Но я не знаю почему,viewWillDisappear () вызывается немедленно, как будто представление было удалено ...

Может ли кто-нибудь мне помочь, пожалуйста?

РЕДАКТИРОВАТЬ:

Мой первый просмотр:

#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

Мой второй взгляд:

#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

Если честно, этот проект очень большой, я начал над ним работать 2 месяца назад, и я один над ним работаю.Я не работал в Objective-C раньше и еще меньше с X-Code.Я постепенно открываю для себя возможности и Objective-C ...

1 Ответ

0 голосов
/ 28 мая 2018

В вашем первом VC вы звоните [self.navigationController popViewControllerAnimated:YES];, который сообщает навигационному виртуальному каналу выдвигать видимый в данный момент контроллер представления.Если вы установите точки останова на tableview didSelectRowAtIndexPath: в первом VC и на viewDidLoad во втором VC, вы увидите, в каком порядке они называются.У меня такое ощущение, что порядок выполнения может быть следующим:

  1. подготовка к переходу в первом VC
  2. представление загружено во втором VC
  3. didSelectRowAtIndexPath в первом VC
  4. наконец-то ваш второй VC выгружается

Это моя идея без тестирования.Пожалуйста, убедитесь, что вам действительно нужно вставить VC в didSelectRow

...