iOS - 为什么我的下一个视图回调我之前的视图?

iOS - Why my next view callback my previous view?

我的情况是下一个:
我有两个视图控制器。 第一个包含 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...

在您的第一个 VC 中,您调用 [self.navigationController popViewControllerAnimated:YES]; 告诉导航 VC 弹出当前可见的视图控制器。如果您将断点设置为第一个 VC 中的 tableview didSelectRowAtIndexPath: 和第二个 VC 中的 viewDidLoad,您将看到它们的调用顺序。我感觉执行顺序可能是这样的:

  1. 首先准备segueVC
  2. 视图在第二秒加载完毕VC
  3. didSelectRowAtIndexPath 在第一个 VC
  4. 你的第二个 VC 终于卸载了

这是我的想法,没有经过测试。请确保您确实需要在 didSelectRow

中弹出 VC