ios - UITableView 重复 Firebase 数据
<p><p>我从 Firebase 收到重复的内容,但我似乎无法弄清楚我做错了什么。在 firebase 我有 6 个帖子。 tableview 正在填充 6 个单元格,但所有 6 个单元格都具有相同的数据,并且其他 5 个帖子不存在。 </p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
RankingsCell *cell = ;
self.ref = [ reference];
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 = ;
cell.usernameOutlet.text = username;
cell.dateOutlet.text = date;
cell.combatPowerLabel.text = ;
cell.pokemonLabel.text = pokemon;
;
;
}
}
withCancelBlock:^(NSError * _Nonnull error)
{
NSLog(@"%@", error.localizedDescription);
}];
return cell;
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p><code>cellForRowAtIndex:</code> 方法为“每个”单元格调用,因此您不应该在那里进行数据库工作,它只负责一次创建“一个”单元格。</code> p>
<p>因此,将您的 <code>observeEventType:</code> 调用移动到 <code>viewDidLoad:</code> 或 <code>viewDidAppear:</code> 中,例如:</p>
<pre><code>- (void)viewDidLoad
{
;
self.ref = [ reference];
posts = ;
[posts observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot)
{
self.allSnapshots = ;
for (snapshot in snapshot.children)
{
;
}
; // Refresh table view after getting data
} // .. error ...
}
</code></pre>
<p>而在<code>numberOfRowsForInSection:</code></p>
<pre><code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return ;
}
</code></pre>
<p>而在 <code>cellForRowAtIndex:</code></p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
RankingsCell *cell = ;
FIRDataSnapshot *snapshot = ;
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 = ;
cell.usernameOutlet.text = username;
cell.dateOutlet.text = date;
cell.combatPowerLabel.text = ;
cell.pokemonLabel.text = pokemon;
;
;
return cell;
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - UITableView 重复 Firebase 数据,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/40317448/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/40317448/
</a>
</p>
页:
[1]