Добавление новой строки в UITableView - PullRequest
0 голосов
/ 15 сентября 2010

Привет всем,

Это мой первый пост здесь, и это моя проблема: Я пытаюсь получить некоторые данные из вызова API REST и затем показать их в UITableView.

Вот что я делаю:

в viewDidLoad: 1) здесь я инициализирую свой массив вещей , чтобы показать в таблице (которая пуста в начале) 2) таблица загружается (с 0 строками) и 3) затем выполняется асинхронный вызов HTTP.

Сделав это, я делаю свои вещи с помощью HTTP Response, и когда я готов, я вызываю reloadData в моей таблице. Здесь происходит странное.

numberOfRowsInSelection возвращает мне правильное количество строк но tableView: cellForRowAtIndexPath: indexPath для indexPath.row всегда возвращает мне ноль! поэтому новая строка не добавляется в таблицу.

  - (void)doJSONRequest{
    responseData = [[NSMutableData data] retain];

    NSString *addr = [[NSString alloc] initWithFormat:@"http://localhost:8080/blabla/v1/items?count=10"];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:addr]];

    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [addr release];
}

- (void)doJSONRequestWithURL:(NSString *)url{
    responseData = [[NSMutableData data] retain];

    NSString *addr = [[NSString alloc] initWithFormat:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:addr]];

    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [addr release];
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    //NSLog(@"[%@] connection:didReceiveResponse %@",[self class], response);
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    //NSLog(@"[%@] connection:didReceiveData %@",[self class], data);
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"[%@]",[NSString stringWithFormat:@"Connection failed: %@", [error description]]);
    UIAlertView *alert = [[UIAlertView alloc] init];
    [alert setTitle:@"NETWORK ERROR!"];
    [alert setMessage:@"App will close"];
    [alert setDelegate:self];
    [alert addButtonWithTitle:@"Close"];
    [alert show];
    [alert release];
    [alert show];
    [alert release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {  
    //NSLog(@"[%@] connectionDidFinishLoading %@",[self class], connection);
    [connection release];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [responseData release];

    NSDictionary *res = [NSDictionary dictionaryWithDictionary:[responseString JSONValue]];

    NSDictionary *tmp = [res valueForKey:@"reviews"];
    tmp = [tmp valueForKey:@"reviews"];
    NSEnumerator *e = [tmp objectEnumerator];
    NSDictionary *tmp_review;

    int i=0;
    while (tmp_review = [e nextObject]) {
        //NSLog(@"tmp_review %@", tmp_review);
        //NSLog(@"count %d", i++);

            MyObject r = [... doing my staff...]
        [reviews addObject: r];
        [r release];
    };
    [reviewListTableView reloadData];
    [responseString release];

}

- (void)viewDidLoad {
//- (void)initUI {

    //review is the array where I put my data
    //it is empty at the beginning
    reviews = [[NSMutableArray alloc] initWithObjects:nil];
    [super viewDidLoad];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [reviews count] 
}

Ответы [ 3 ]

0 голосов
/ 25 января 2011

добавить новый объект в массив и [mytableview reloadData];

0 голосов
/ 25 января 2011

Реализация следующего источника данных, возвращающего номер раздела, который должен присутствовать в табличном представлении.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;

В tableView: cellForRowAtIndexPath: indexPath проверяет номер раздела и выполняет вашу операцию.

Примечание:Если вам не нужны разделы, вы можете удалить их.

0 голосов
/ 15 сентября 2010

Звучит так, как будто вы неправильно реализовали numberOfSectionsInTableView:. Вы должны войти indexPath.section в tableView:cellForRowAtIndexPath:indexPath, чтобы увидеть, какое значение раздела вы передаете. У вас будет несколько значений indexPath.row, равных нулю, поскольку для каждого раздела есть нулевая строка.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...