iOS - 为啥我的下一个视图回调我以前的视图?

Posted

技术标签:

【中文标题】iOS - 为啥我的下一个视图回调我以前的视图?【英文标题】:iOS - Why my next view callback my previous view?iOS - 为什么我的下一个视图回调我以前的视图? 【发布时间】:2018-05-28 10:55:52 【问题描述】:

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

说实话,这个项目很大,我从两个月前就开始做,我一个人在做。我之前没有在 Objective-C 中工作,甚至更少使用 X-Code。我正在逐渐发现功能和 Objective-C...

【问题讨论】:

显示您的第二次查看代码 是的,请添加您的第二个视图控制器的完整代码 【参考方案1】:

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

    为 firstVC 中的 segue 做准备 在 secondVC 中确实加载了视图 didSelectRowAtIndexPath 在第一个 VC 中 你的第二个 VC 终于卸载了

这是我的想法,未经测试。请确保您确实需要在 didSelectRow 中弹出 VC

【讨论】:

你的想法是错误的,但它帮助我找到了真正的解决方案,它接近你的想法:我评论了 [self.navigationController popViewControllerAnimated:YES];在我的第一个 VC 中,它可以工作......但我不确定为什么 如果你从单元格到 secondVC 设置一个 segue,则 segue 在 didselectrow 之前被调用,并且当 popViewcontroller 被调用时,你在导航 VC 中有第二个 VC(因此它在 viewDidLoad 之后立即返回)。试试这个:删除你的 segue,创建一个新的 viewController segue(从一个 viewController 拖到另一个并给它一个标识符)。这会改变执行顺序,并且 didselectRow 将在 prepareForSegue 之前被调用。不要忘记在 didSelectRowatIndexPath 方法中调用[self performSegueWithIdentifier:@"Segue" sender:self]

以上是关于iOS - 为啥我的下一个视图回调我以前的视图?的主要内容,如果未能解决你的问题,请参考以下文章

从以前的VIew控制器获取数据

iOS:为啥我的子视图在滚动视图中出现大间距

为啥 viewbag 值不传递回视图?

ios7状态栏在模态视图上变回黑色? [复制]

滑回主视图控制器时的ECSlidingViewController回调?

如何导航回以前加载的 xib 文件?