菜鸟教程小白 发表于 2022-12-12 16:05:44

iphone - 释放tableview ios iphone中的所有单元格


                                            <p><p>我在 xcode 中通过分析发现了内存泄漏问题。这个问题很简单,但我不明白如何解决它:</p>

<p>考虑一个带有 2 个按钮和一个 tableview 的 uiviewcontroller。
button1=从服务器加载 JSON 数据并将单元格添加到 tableview 然后 </p>

<p>button2=从另一个服务器加载 JSON 数据并将单元格添加到 tableview 然后重新加载。</p>

<p>好的,问题出在:</p>

<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
....
.....
NSURL *url = ;
NSData *data = ;
UIImage *img;
if(!data) img=;
else img= [ initWithData:data];
cell.imageView.image = img;
</code></pre>

<p>好的,如果我每次切换时都用 2 个按钮开始切换,我会从 UIImage 泄漏,所以我认为我需要在重新加载之前“清除”(释放)所有单元格数据?</p>

<p>谢谢</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您应该在 <code>cell.imageView.image</code> 中设置后释放 <code>img</code> 对象。我更喜欢 <code>autorelease</code> 在同一行,因为它让我更容易跟踪。</p>

<pre><code>UIImage *img;
if(!data) img=;
else img= [[ initWithData:data] autorelease];
cell.imageView.image = img;
</code></pre>

<p>正如另一个答案中提到的,您可以通过不使用 <code>initWithData</code> 调用,而是使用 <code>imageWithData</code> 来避免痛苦。 </p>

<p>细胞会自己照顾自己。</p></p>
                                   
                                                <p style="font-size: 20px;">关于iphone - 释放tableview ios iphone中的所有单元格,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/5395558/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/5395558/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: iphone - 释放tableview ios iphone中的所有单元格