UITableView重复Firebase数据

我正在从Firebase获取重复的内容,而我似乎无法弄清楚我做错了什么。 在firebase我有6个职位。 tableview是填充6个单元格,但所有6个单元格具有相同的数据,其他5个职位不在那里。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { RankingsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RankingsCell"]; self.ref = [[FIRDatabase database] reference]; posts = [ref child:@"posts"]; [posts observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) { for (snapshot in snapshot.children) { NSString *username = snapshot.value[@"Name"]; NSString *date = snapshot.value[@"Date"]; NSString *combatPower = snapshot.value[@"Combat Power"]; NSString *pokemon = snapshot.value[@"Pokemon"]; NSString *pokemonURL = snapshot.value[@"Pokemon Image"]; NSString *picURL = snapshot.value[@"Profile Picture"]; int CP = [combatPower intValue]; cell.usernameOutlet.text = username; cell.dateOutlet.text = date; cell.combatPowerLabel.text = [NSString stringWithFormat:@"COMBAT POWER: %d", CP]; cell.pokemonLabel.text = pokemon; [cell downloadUserImage:picURL]; [cell downloadPokemonImage:pokemonURL]; } } withCancelBlock:^(NSError * _Nonnull error) { NSLog(@"%@", error.localizedDescription); }]; return cell; } 

cellForRowAtIndex:方法被称为“每个”单元格,所以你不应该在那里做你的数据库工作,它只是负责一次创build“一个”单元格。

因此,在viewDidLoad:viewDidAppear:移动您的observeEventType: call viewDidAppear: like:

 - (void)viewDidLoad { [super viewDidLoad]; self.ref = [[FIRDatabase database] reference]; posts = [ref child:@"posts"]; [posts observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) { self.allSnapshots = [NSMutableArray array]; for (snapshot in snapshot.children) { [self.allSnapshots addObject:snapshot]; } [self.tableView reloadData]; // Refresh table view after getting data } // .. error ... } 

并在numberOfRowsForInSection:

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.allSnapshots count]; } 

cellForRowAtIndex:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { RankingsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RankingsCell"]; FIRDataSnapshot *snapshot = [self.allSnapshots objectAtIndex:indexPath.row]; NSString *username = snapshot.value[@"Name"]; NSString *date = snapshot.value[@"Date"]; NSString *combatPower = snapshot.value[@"Combat Power"]; NSString *pokemon = snapshot.value[@"Pokemon"]; NSString *pokemonURL = snapshot.value[@"Pokemon Image"]; NSString *picURL = snapshot.value[@"Profile Picture"]; int CP = [combatPower intValue]; cell.usernameOutlet.text = username; cell.dateOutlet.text = date; cell.combatPowerLabel.text = [NSString stringWithFormat:@"COMBAT POWER: %d", CP]; cell.pokemonLabel.text = pokemon; [cell downloadUserImage:picURL]; [cell downloadPokemonImage:pokemonURL]; return cell; }