Подтвердить что ты не робот

Ошибка создания строки в tableview

Ошибка создания строки в представлении таблицы.

В моем представлении таблицы есть json.

Здесь я видел много примеров, однако никто не смог решить

мой код

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];

отображается ошибка

2013-05-30 23: 15: 17.345 lerJson [1141: c07] * Ошибка утверждения в - [UITableView _endCellAnimationsWithContext:],/SourceCache/UIKit_Sim/UIKit-2380.17/UITableView.m:908 Причина: "попытаться вставить строку 11 в раздел 1, но есть только 1 секция после того, как вы закончили приложение" исключение "NSInternalInconsistencyException. Обновить' ** Первый стек вызовов броска: (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) libС++ abi.dylib: завершение вызова throwing exception

Мой полный код 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

Моя делегация не изменила

4b9b3361

Ответ 1

Вам также необходимо обновить свой источник данных следующим образом: [news insertObject:@"teste" atIndex:0];

Я предполагаю, что у вас есть только 1 раздел.

измените этот код: NSMutableArray *path = [NSMutableArray arrayWithObject:[NSIndexPath indexPathForRow:[news count] inSection:1]];

к этому коду: NSMutableArray *path = [NSMutableArray arrayWithObject:[NSIndexPath indexPathForRow:[news count] inSection:0]];

разделы и строки начинаются с 0.