2015-12-01 3 views
1

Здравствуйте, у меня есть табличное представление с пользовательской ячейкой, и я хочу, чтобы в реальном времени обновлял мои коды.Objective-c TableView реального времени обновить пользовательские ячейки

 @interface ViewController() <UITableViewDataSource, UITableViewDelegate> 

     @property (nonatomic, strong) NSMutableArray *jsonArray; 
     @property (nonatomic, strong) NSMutableArray *array1; 
     @property (nonatomic, strong) NSDictionary *entryDict; 

     @end 


     - (void)viewDidLoad { 
      [super viewDidLoad]; 

     _tableView.delegate = self; 
      [self refresh]; 
     } 

     - (void)refresh 
     { 
      NSString *urlduzenli = [NSString stringWithFormat:@"http://bla.com/server/table.php?OrderId=%@",suankioturumid]; 
      NSURL * url = [NSURL URLWithString:urlduzenli]; 

      NSURLRequest * urlReq = [NSURLRequest requestWithURL:url]; 

      NSError * error; 

      NSData * data = [NSURLConnection sendSynchronousRequest:urlReq returningResponse:nil error:&error]; 

      if (!error) { 
       NSDictionary * jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; 

       _jsonArray = [jsonDict objectForKey:@"orders"]; 

       _array1 =[[NSMutableArray alloc]init]; 

      }else{ 

      } 
    [self.tableView reloadData]; 
      } 

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

      return _jsonArray.count; 
     } 

     - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
     { 
      static NSString *[email protected]"CustomCell"; 
      CustomTableViewCell *cell=(CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid];; 

      if(cell==nil) 
      { 
       cell=[[CustomTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid]; 

      } 

      _entryDict= _jsonArray[indexPath.row]; 
      NSString *countryName = _entryDict[@"order"]; 

      NSMutableSet *seenCharacters = [NSMutableSet set]; 
      NSMutableString *resultf = [NSMutableString string]; 

       cell.nameLabel.text= countryName; 


    if([cell.nameLabel.text isEqualToString:@"1"]){ 

     cell.nameLabel.backgroundColor = [UIColor redColor]; 

    }else{ 

      } 

      return cell; 
     } 

Коды успеха в работе Мне нужно только обновлять таблицы в реальном времени. Im все еще работающ около 8-10 часов но я не разрешил его.

Не обновляйте каждую ячейку

(мою ошибку это: Показаны красного фона на неправильных строках при добавлении новых строк)

if([cell.nameLabel.text isEqualToString:@"1"]){ 

    cell.nameLabel.backgroundColor = [UIColor redColor]; 
} 

Спасибо за помощь! Спасибо

+0

Итак, что конкретно представляет собой ваш вопрос? Вы просто хотите обновить данные во всей таблице? Один ряд? –

+0

@MSU_Bulldog весь стол чувак – SwiftDeveloper

+0

Существует метод для этого ... '[tableView reloadData];' –

ответ

0

Исходя из нашей дискуссии в комментариях, здесь приведены некоторые варианты решения проблемы.

1) Вы должны добавить UITableView делегат, где это говорит <UITableViewDataSource, UITableViewDelegate> затем установить tableView.delegate = self; в viewDidLoad

2) Новая проблема, вы столкнулись, скорее всего, лежит в коде, вы не размещаете где вы измените значения в _jsonArray. Я бы сделал NSLog значений _jsonArray для каждой строки, чтобы убедиться, что номер строки соответствует правильному элементу в _jsonArray. Попробуйте установить cell.nameLabel.backgroundColor = [UIColor clearColor] в разделе else вашего оператора if.

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