Error creating row in tableview
Asked Answered
G

1

0

Error creating row in tableview.

My table view is loaded with a json.

I saw many examples here, however none were able to solve

my code

NSMutableArray *myArray = [NSMutableArray arrayWithArray:news];
        [myArray insertObject:@"teste" atIndex:0];
        NSMutableArray *path = [NSMutableArray arrayWithObject:[NSIndexPath indexPathForRow:[news count]-1 inSection:1]];
        [self.tableView insertRowsAtIndexPaths:path withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView endUpdates];

error displayed

2013-05-30 23:15:17.345 lerJson[1141:c07] * Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-2380.17/UITableView.m:908 2013-05-30 23:15:17.347 lerJson[1141:c07] Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert row 11 into section 1, but there are only 1 sections after the update' ** First throw call stack: (0x1c95012 0x10d2e7e 0x1c94e78 0xb68665 0xb670b 0xc4945 0xc4973 0x476d 0x76d78 0x789eb 0x2e185a 0x2e099b 0x2e20df 0x2e4d2d 0x2e4cac 0x2dca28 0x49972 0x49e53 0x27d4a 0x19698 0x1bf0df9 0x1bf0ad0 0x1c0abf5 0x1c0a962 0x1c3bbb6 0x1c3af44 0x1c3ae1b 0x1bef7e3 0x1bef668 0x16ffc 0x26ad 0x25d5) libc++abi.dylib: terminate called throwing an exception

My full code j2_ViewController.h

#import "j2_ViewController.h"

@interface j2_ViewController ()

@end

@implementation j2_ViewController



- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self carregaDados];

}

-(void)carregaDados
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;


    NSURL *url2 = [[NSURL alloc] initWithString:[@"http://localhost:3000/json.aspx?ind=0&tot=12" stringByAddingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding]];

    NSURLRequest *request = [NSURLRequest requestWithURL:url2];

    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}



-(void)carregaDados2
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;


    NSURL *url2 = [[NSURL alloc] initWithString:[@"http://localhost:3000/json.aspx?ind=12&tot=12" stringByAddingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding]];

    NSURLRequest *request = [NSURLRequest requestWithURL:url2];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSError *jsonParsingError = nil;

    NSMutableData *myData = [[NSMutableData alloc]init];
    [myData appendData:response];


    NSMutableArray *news2;

    news2 = [NSJSONSerialization JSONObjectWithData:myData options:nil error:&jsonParsingError];
    //NSLog(@"LOG: %@", news2);


    NSMutableArray *myArray = [NSMutableArray arrayWithArray:news];
    [myArray addObjectsFromArray:news2];

    NSLog(@"LOG: %@", myArray);

    news = myArray;

    //NSLog(@"Erro: %@", jsonParsingError);
    [tableViewjson reloadData];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    data = [[NSMutableData alloc]init];
}

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    NSError *e = nil;
    news = [NSJSONSerialization JSONObjectWithData:data options:nil error:&e];

    [tableViewjson reloadData];
    //NSLog(@"erro=%@",e);

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Erro" message:@"Não foi possivle fazer o download - cheque sua conexão 3g ou wi-fi" delegate:nil cancelButtonTitle:@"cancelar" otherButtonTitles:nil];
    [alert show];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

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

#pragma mark - Table view data source

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSInteger teste = [news count];
    return teste;
}

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"nome"];

    return cell;
}

//chama essa função quando o scroll atinge seu final
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{

    NSInteger currentOffset = scrollView.contentOffset.y;
    NSInteger maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height;

    if(maximumOffset - currentOffset <= -40)
    {
       //carega mais dados
        //[self carregaDados2];
        [self.tableView beginUpdates];



        NSMutableArray *myArray = [NSMutableArray arrayWithArray:news];
        [myArray insertObject:@"teste" atIndex:0];
        NSMutableArray *path = [NSMutableArray arrayWithObject:[NSIndexPath indexPathForRow:[news count]-1 inSection:1]];
        [self.tableView insertRowsAtIndexPaths:path withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView endUpdates];
    }
}



@end

My delegation has not changed

Gamba answered 31/5, 2013 at 2:34 Comment(2)
how many sections do you have? maybe you can post your tableview delegate and datasource codeSelector
Sections start at 0, not 1. Also, you add @"teste" to a temporary array. You need to add it to the actual array used by your data source methods before you call endUpdates.Modifier
S
1

You also need to update your datasource like this: [news insertObject:@"teste" atIndex:0];

I assume you only have 1 section.

change this code: NSMutableArray *path = [NSMutableArray arrayWithObject:[NSIndexPath indexPathForRow:[news count] inSection:1]];

to this code: NSMutableArray *path = [NSMutableArray arrayWithObject:[NSIndexPath indexPathForRow:[news count] inSection:0]];

sections and rows starts at 0.

Selector answered 31/5, 2013 at 3:0 Comment(6)
I made the alteration, returned the following error: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (12) must be equal to the number of rows contained in that section before the update (12), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'Gamba
@Gamba See my earlier comment under your question. You are not properly updating your data source array. That is the cause of this error.Modifier
@Gamba updated my answer kindly check and rmaddy is right you also need to update your data source before making the tableview updateSelector
I see what returns: 2013-05-31 09:28:26.479 lerJson[538:c07] Exception: attempt to insert row 12 into section 0, but there are only 12 rows in section 0 after the updateGamba
[news insertObject:@"teste" atIndex:0]; return error:: 2013-05-31 10:03:25.180 lerJson [670: c07] Exception: - [__NSCFArray insertObject: atIndex]: método mutante enviado para imutável objetoGamba
@Gamba based on [__NSCFarray insertObject:atIndex] error means you are inserting an object in an NSArray convert it to NSMutableArray.Selector

© 2022 - 2024 — McMap. All rights reserved.