2016-11-10 4 views
2

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

{ 
    Name = "American Airlines"; 
    Picture =   (
      "" 
    ); 
    Rate = 3; 
    }, 

И я хочу, чтобы показать имя на этикетке ячейки ... для которого я делаю следующий код:

-(void)viewWillAppear:(BOOL)animated 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDetail:) name:@"NewNotification" object:nil]; 

} 

-(void)getDetail:(NSNotification *)notification 
{ 

    if([notification.name isEqualToString:@"NewNotification"]) 
    { 
     NSDictionary *dictionary=notification.userInfo; 
     NSLog(@"Dictionary %@",dictionary); 
     userInfo=dictionary; 
     [self.listView reloadData]; 

    } 


} 


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    //return [userInfo count]; 
    return 115; 
} 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 

    static NSString *[email protected]"cell"; 
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (cell== nil) { 

     cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
    } 

    cell.Name.text =[userInfo valueForKey:@"Name"]; 

    NSLog(@"the cell.Name.text is %@",cell.Name.text); 
    //[cell updateCell:userInfo]; 
    return cell; 

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

} 

Я не могу понять, что я делаю неправильно в коде, как он выходит из строя, и ничего на label.It не показываю даю, за исключением

«Нагрузочное приложение из-за неперехваченное исключение„NSInvalidArgumentException“, причина:„- [__ длина NSArrayI]: непризнанный селектор направил к экземпляру 0x7bea2d20“»

Пожалуйста, проверьте код и скажи мне, где я буду неправильно!

+0

добавить исключительную точку останова и посмотреть, где она падает. –

+0

, чтобы узнать, как добавить исключительные точки останова, вы можете увидеть http://stackoverflow.com/questions/17802662/exception-breakpoint-in-xcode. его очень легко сделать. –

ответ

1

В коде есть проблема синтаксического анализа. Возьмите глобальный массив в своем классе под названием arrList. Пожалуйста, обновите код

if([notification.name isEqualToString:@"NewNotification"]) 
    { 
     NSDictionary *dictionary=notification.userInfo; 
     NSLog(@"Dictionary %@",dictionary); 
     userInfo=dictionary; 
     [self.listView reloadData]; 

    } 

с этим:

if([notification.name isEqualToString:@"NewNotification"]) 
     { 
      NSDictionary *dictionary=notification.userInfo; 
      NSLog(@"Dictionary %@",dictionary); 
      [arrList addObject: dictionary]; 
      [self.listView reloadData]; 

     } 

Когда мы называем вебсервис, массив будет добавить словарь.

Теперь измените строку кода для Tableview:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    //return [userInfo count]; 
    return 115; 
} 

С этим одним:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 

     return [arrList count]; 
    } 

И я добавляю несколько строк кода в методе Tableview cellForRowAtIndexPath:

-(UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 

    static NSString *[email protected]"cell"; 
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (cell== nil) { 

     cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
    } 
    if(arrList.count > 0){ 
     NSDictonary * dict = arrList[indexPath.row]; 
     cell.Name.text =[dict valueForKey:@"Name"]; 

     NSLog(@"the cell.Name.text is %@",cell.Name.text); 
     //[cell updateCell:userInfo]; 
    } 
    return cell; 

}

Теперь он исправит ваш сбой.

+0

Я пробовал этот код, но он не добавляет какой-либо элемент словаря в список и показывает arrlist как nil, тогда как он показывает 117 значений в словаре – FreshStar

+0

Возможно ли, что вы можете показать мне скриншот или ответ 117 значений ..? –

+0

Извините, вы не можете использовать словарь, но он возвращает 117 значений, подобных этому { Name = "American Airlines"; Picture = ( "" ); Ставка = 3; } – FreshStar