2015-09-22 2 views
-1

У меня ошибка, когда я нажимаю на последнюю ячейку моего табличного представления. В ней говорится, что я обращаюсь к чему-то за облигациями, но не могу понять, какой массив я «Неправильно. Он работает правильно, когда я нажимаю на другие ячейки, это только последняя проблема. Я думаю, что ошибка исходит из моего метода prepareforsegue. Я поставил точки останова повсюду, но ошибка возникает, когда он выходит из метода prepareforsegue.Ошибка: завершение приложения из-за неперехваченного исключения «NSRangeException»

Я получаю json-файл из веб-службы, которую я разбираю и помещаю в таблицу. Когда пользователь нажимает на ячейку, я нажимаю на другой диспетчер представлений с помощью segue из моей раскадровки, я отправляю информацию на этот новый диспетчер представлений и отображаю его пользователю. В предыдущем проекте я использовал ту же логику и почти идентичные методы, и он работал нормально.

Это моя ошибка:

2015-09-22 09:39:07.900 Deblocage[4745:607] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 6 beyond bounds [0 .. 5]' 
*** First throw call stack: 
(
    0 CoreFoundation      0x0078c1e4 __exceptionPreprocess + 180 
    1 libobjc.A.dylib      0x0050b8e5 objc_exception_throw + 44 
    2 CoreFoundation      0x0072d3f6 -[__NSArrayM objectAtIndex:] + 246 
    3 Deblocage       0x0004df2e -[JournalDesCommandesPBViewController prepareForSegue:sender:] + 1726 
    4 UIKit        0x00f57efa -[UIStoryboardSegueTemplate _perform:] + 156 
    5 UIKit        0x00f57f87 -[UIStoryboardSegueTemplate perform:] + 115 
    6 UIKit        0x00add965 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1453 
    7 UIKit        0x00addb14 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 279 
    8 UIKit        0x00ae210e __38-[UITableView touchesEnded:withEvent:]_block_invoke + 43 
    9 UIKit        0x00a110aa ___afterCACommitHandler_block_invoke + 15 
    10 UIKit        0x00a11055 _applyBlockToCFArrayCopiedToStack + 403 
    11 UIKit        0x00a10e76 _afterCACommitHandler + 532 
    12 CoreFoundation      0x0075436e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30 
    13 CoreFoundation      0x007542bf __CFRunLoopDoObservers + 399 
    14 CoreFoundation      0x00732254 __CFRunLoopRun + 1076 
    15 CoreFoundation      0x007319d3 CFRunLoopRunSpecific + 467 
    16 CoreFoundation      0x007317eb CFRunLoopRunInMode + 123 
    17 GraphicsServices     0x02a4a5ee GSEventRunModal + 192 
    18 GraphicsServices     0x02a4a42b GSEventRun + 104 
    19 UIKit        0x009f3f9b UIApplicationMain + 1225 
    20 Deblocage       0x0004e67a main + 138 
    21 libdyld.dylib      0x0267e6d9 start + 1 
    22 ???         0x00000001 0x0 + 1 
) 
libc++abi.dylib: terminating with uncaught exception of type NSException 

Это мой класс:

#import "JournalDesCommandesPBViewController.h" 
#import "Constantes.h" 
#import "JournalDesCommandesPBTableViewCell.h" 
#import "JournalDesCommandesDetailViewController.h" 

@interface JournalDesCommandesPBViewController() 
{ 
    NSMutableArray *nomClient; 
    NSMutableArray *numCommandeType; 
    NSMutableArray *site; 
    NSMutableArray *modeCmdQualiteNat; 
    NSMutableArray *dateSaisie; 
    NSMutableArray *datePrevue; 
    NSMutableArray *qualiteDesc; 
    NSMutableArray *poids; 
    NSMutableArray *montant; 
} 


@property (nonatomic, strong) id jsonArray; 

@property (nonatomic, strong) UIRefreshControl *refreshControl; 

@end 

@implementation JournalDesCommandesPBViewController 

@synthesize jsonArray; 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    [self.tableData setDelegate:self]; 
    [self.tableData setDataSource:self]; 

    self.refreshControl = [[UIRefreshControl alloc] init]; 

    [self.refreshControl addTarget:self action:@selector(refreshData) forControlEvents:UIControlEventValueChanged]; 

    [self.tableData addSubview:self.refreshControl]; 

    [self.tableData reloadData]; 

} 

-(void) viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 

    [self.navigationController.navigationBar setHidden:NO] ; 
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil]; 
    [self refreshData]; 
    // self.navigationItem.hidesBackButton = YES; 
} 


//refresh data 
-(void) refreshData 
{ 

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
    NSString *ID_CLIENT = [defaults objectForKey:@"ID_CLIENT"]; 

    [self.connection cancel]; 

    NSMutableData *data = [[NSMutableData alloc] init]; 
    self.receivedData = data; 

    NSURL *url = [NSURL URLWithString:URL]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]]; 
    [request setHTTPMethod:@"POST"]; 
    NSString *postData = [[NSString alloc] initWithFormat:@"listeCommande\",\"%@,;-1,;PB,;-1",ID_CLIENT]; 
    [request setValue:@"application/raw; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 

    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]]; 

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    self.connection = connection; 

    [connection start]; 

} 


// télecharger data 

-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSError *e = nil; 

    jsonArray = [NSJSONSerialization JSONObjectWithData:self.receivedData options:NSJSONReadingMutableContainers error: &e]; 

    NSDictionary *tempJson = jsonArray; 

    NSString *firstId =jsonArray[0][@"idCmd"]; 

    nomClient = [[NSMutableArray alloc] init]; 
    numCommandeType = [[NSMutableArray alloc] init]; 
    site = [[NSMutableArray alloc] init]; 
    modeCmdQualiteNat = [[NSMutableArray alloc] init]; 
    dateSaisie = [[NSMutableArray alloc] init]; 
    datePrevue = [[NSMutableArray alloc] init]; 
    qualiteDesc = [[NSMutableArray alloc] init]; 
    poids = [[NSMutableArray alloc] init]; 
    montant = [[NSMutableArray alloc] init]; 

    NSMutableArray *tempId = [[NSMutableArray alloc] init]; 
    [tempId addObject:firstId]; 

    NSString *tempNomClient = [[NSString alloc] initWithFormat:@"%@ (%@)",jsonArray[0][@"nomClient"],jsonArray[0][@"codeClient"]]; 
    NSString *tempNumCommandeType = [[NSString alloc] initWithFormat:@"%@ - %@",jsonArray[0][@"numCommande"], jsonArray[0][@"typeCommande"]]; 
    NSString *tempSite = [[NSString alloc] initWithFormat:@"%@",jsonArray[0][@"site"]]; 
    NSString *tempModeCommandeQualiteNat = [[NSString alloc] initWithFormat:@"%@/%@",jsonArray[0][@"modeCmd"],jsonArray[0][@"qualiteNat"]]; 
    NSString *tempDateSaisie = [[NSString alloc] initWithFormat:@"Saisie le : %@",jsonArray[0][@"dateSaisie"]]; 
    NSString *tempDatePrevue = [[NSString alloc] initWithFormat:@"Prevue le : %@",jsonArray[0][@"datePrevue"]]; 
    NSString *tempQualiteDesc = [[NSString alloc] initWithFormat:@"%@",jsonArray[0][@"qualiteDesc"]]; 
    NSString *tempPoids = [[NSString alloc] initWithFormat:@"%@ %@",jsonArray[0][@"quantite"],jsonArray[0][@"uMesure"]]; 

    NSString *tempMontant = [[NSString alloc] initWithFormat:@"%@",jsonArray[0][@"montant"]]; 

    NSNumberFormatter *formatter = [NSNumberFormatter new]; 
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; 
    NSString *montant_data = [formatter stringFromNumber:[NSNumber numberWithInteger:(int)tempMontant]]; 
    montant_data = [montant_data stringByReplacingOccurrencesOfString:@"," withString:@" "]; 


    [nomClient addObject:tempNomClient]; 
    [numCommandeType addObject:tempNumCommandeType]; 
    [site addObject:tempSite]; 
    [modeCmdQualiteNat addObject:tempModeCommandeQualiteNat]; 
    [dateSaisie addObject:tempDateSaisie]; 
    [datePrevue addObject:tempDatePrevue]; 
    [qualiteDesc addObject:tempQualiteDesc]; 
    [poids addObject:tempPoids]; 



    // YES YES YES 
    for (int i = 1; i < (unsigned long)tempJson.count; i++) { 

     NSString *idCmd_data = jsonArray[i][@"idCmd"]; 

     if (![tempId containsObject:idCmd_data]) 
     { 
      [tempId addObject:idCmd_data]; 

      tempNomClient = [[NSString alloc] initWithFormat:@"%@ (%@)",jsonArray[i][@"nomClient"],jsonArray[i][@"codeClient"]]; 
      tempNumCommandeType = [[NSString alloc] initWithFormat:@"%@ - %@",jsonArray[i][@"numCommande"], jsonArray[i][@"typeCommande"]]; 
      tempSite = [[NSString alloc] initWithFormat:@"%@",jsonArray[i][@"site"]]; 
      tempModeCommandeQualiteNat = [[NSString alloc] initWithFormat:@"%@/%@",jsonArray[i][@"modeCmd"],jsonArray[i][@"qualiteNat"]]; 
      tempDateSaisie = [[NSString alloc] initWithFormat:@"Saisie le : %@",jsonArray[i][@"dateSaisie"]]; 
      tempDatePrevue = [[NSString alloc] initWithFormat:@"Prevue le : %@",jsonArray[i][@"datePrevue"]]; 
      NSString *tempQualiteDesc = [[NSString alloc] initWithFormat:@"%@",jsonArray[i][@"qualiteDesc"]]; 
      NSString *tempPoids = [[NSString alloc] initWithFormat:@"%@ %@",jsonArray[i][@"quantite"],jsonArray[0][@"uMesure"]]; 

      tempMontant = [[NSString alloc] initWithFormat:@"%@",jsonArray[i][@"montant"]]; 

      NSNumberFormatter *formatter = [NSNumberFormatter new]; 
      [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; 
      NSString *montant_data = [formatter stringFromNumber:[NSNumber numberWithInteger:(int)tempMontant]]; 
      montant_data = [montant_data stringByReplacingOccurrencesOfString:@"," withString:@" "]; 

      /* 
      format date : dd/MM/yyyy 
      tempDateSaisie = [[NSString alloc] initWithFormat:@"%@",jsonArray[i][@"dateSaisie"]]; 
      NSArray *temp = [tempDateSaisie componentsSeparatedByString:@"-"]; 
      tempDateSaisie = [[NSString alloc] initWithFormat:@"Saisie le : %@/%@/%@", temp[2], temp[1], temp[0]]; 
      */ 

      [nomClient addObject:tempNomClient]; 
      [numCommandeType addObject:tempNumCommandeType]; 
      [site addObject:tempSite]; 
      [modeCmdQualiteNat addObject:tempModeCommandeQualiteNat]; 
      [dateSaisie addObject:tempDateSaisie]; 
      [datePrevue addObject:tempDatePrevue]; 
      [qualiteDesc addObject:tempQualiteDesc]; 
      [poids addObject:tempPoids]; 
      [montant addObject:montant_data]; 
     } 
    } 


    [self.tableData reloadData]; 

    [self.refreshControl endRefreshing]; 

} 


-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [self.receivedData appendData:data]; 
} 

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    NSLog(@"connection error = %@" , error); 
} 




// tableData methods 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return (nomClient.count); 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return 100; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    JournalDesCommandesPBTableViewCell *customCell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (indexPath.row % 2) { 
     customCell.contentView.backgroundColor = [UIColor colorWithRed:0.929 green:0.941 blue:0.937 alpha:1]; 
    } else { 
     customCell.contentView.backgroundColor = [UIColor whiteColor]; 

    } 

    if (customCell == nil) 
    { 
     customCell = [[JournalDesCommandesPBTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 

    //NSLog(@"Nom Client : %d - %@", nomClient.count , nomClient[0]); 


    if (nomClient.count > 0) 
    { 
     for (int i = 0; i < nomClient.count; i++) { 

     } 
    } 

    customCell.customNom.text = [nomClient objectAtIndex:indexPath.row]; 
    customCell.customSite.text = [site objectAtIndex:indexPath.row]; 
    customCell.customNumCommandeType.text = [numCommandeType objectAtIndex:indexPath.row]; 
    customCell.customModeCmdQualiteNat.text = [modeCmdQualiteNat objectAtIndex:indexPath.row]; 
    customCell.customDatePrevue.text = [datePrevue objectAtIndex:indexPath.row]; 
    customCell.customDateSaisie.text = [dateSaisie objectAtIndex:indexPath.row]; 


    return customCell; 
} 


- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (IBAction)homeTapped:(id)sender { 
    [self performSegueWithIdentifier:@"JournalDesCommandesPBToAccueil" sender:self]; 
} 


-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 

    //NSLog(@"%@", [numCommandeType objectAtIndex:5]); 
    NSLog(@"%d -- %@",numCommandeType.count ,[numCommandeType objectAtIndex:6]); 

    NSIndexPath *path = [self.tableData indexPathForSelectedRow]; 

    if ([segue.identifier isEqualToString:@"JournalToDetail"] && nomClient.count > (path.row)) 
    { 
     NSLog(@"%d", path.row); 
     JournalDesCommandesDetailViewController *destViewController = segue.destinationViewController; 

     destViewController.nomClientS = [nomClient objectAtIndex:path.row]; 
     destViewController.numCommandeTypeS = [numCommandeType objectAtIndex:path.row]; 
     destViewController.siteS = [site objectAtIndex:path.row]; 
     destViewController.modeCmdQualiteNatS = [modeCmdQualiteNat objectAtIndex:path.row]; 
     destViewController.dateSaisieS = [dateSaisie objectAtIndex:path.row]; 
     destViewController.datePrevueS = [datePrevue objectAtIndex:path.row]; 
     destViewController.poidsS = [poids objectAtIndex:path.row]; 
     destViewController.qualiteDescS = [qualiteDesc objectAtIndex:path.row]; 
     destViewController.montantS = [montant objectAtIndex:path.row]; 

    } 
} 

Edit: Краш заявление Xcode: destViewController.montantS = [montant objectAtIndex:path.row];

+0

Который является утверждение, при котором происходит сбой? Кроме того, пожалуйста, предоставьте зарегистрированные записи перед сбоем. –

+0

, пожалуйста, проверьте значение для 'nomClient.count> (path.row)' & 'indexPathForSelectedRow' –

+0

@Ishanhanda Он вылетает в последней строке метода prepareforsegue: 'destViewController.montantS = [montant objectAtIndex: path.row];' – enzo

ответ

0

Добавить точку останова всех цель исключения C в Xcode и вы увидите, где произошла авария. Более подробную информацию о том, как добавить его можно найти here

+0

Он выходит из строя в последней строке prepareforsegue: 'destViewController.montantS = [montant objectAtIndex: path.row];' – enzo

+0

Очевидным было бы добавить инструкцию NSLog, которая показывает montant.count и path.row. – gnasher729

+0

Там вы идете, массив montantS не имеет объекта по индексу path.row. – Istvan

0

Индексы массивов нуля

for (int i = 0; i < (unsigned long)tempJson.count; i++) { 
+0

Спасибо, но он этого не сделал – enzo

Смежные вопросы