2014-03-06 73 views
0

我正在處理一個沒有ARC的舊項目。它有很多bug,代碼看起來很醜,我正在重寫它。UITableViewCell標識符無ARC泛洪內存

快速瀏覽一下我的代碼

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [self.table dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) 
    { 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 

    cell = [self createCellWithInfo:[self.search objectAtIndex:indexPath.row]]; 
    return cell; 
} 

-(UITableViewCell *)createCellWithInfo:(NSDictionary *)info{ 

    UITableViewCell * cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@「Cell」] autorelease]; 
    //set image for cell 
    //set text for cell.textlabel 
    //set text for cell.detailTextLabel 
    //create an UIButton and add to cell.content view 
    return cell; 
} 

點是在這行代碼 [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@「Cell」] autorelease]

如果我使用@"Cell"這裏,那麼內存就會上升,當我向上滾動並連續倒在桌子上。 經過約15秒的滾動,我的iphone 5c變得滯後。

如果我將它設置爲nil,一切都很好。

有人可以解釋這個嗎?我不是非ARC的familliar。

謝謝。

+0

目標C來評價一個好的做法是什麼是零是:''如果不是'如果(細胞==零)' –

+2

(細胞!)除非有充分的理由不點擊「編輯 - >轉換爲Obj-C ARC」? –

+3

我同意@MikePollard,我敢打賭,這個應用程序泄漏比愛德華斯諾登多。 –

回答

0
UITableViewCell *cell = [self.table dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil){ 
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
} 

單獨照顧小區初始化,您不需要其他線路。

+0

..但它應該可能有一個autorelease無論如何。 –

+0

@JamesWebster是真的。我非ARC'd已經很長時間了! :) –

5

if塊內部,您正在創建單元而不調用autorelease,這會在沒有ARC的情況下泄漏內存。

if塊之後,無論如何您都在重新創建它(無論它是否被回收),這次使用autorelease,您應該真正在做的就是重置其相關​​屬性,以便您可以成功重用循環單元或者配置一個新的單元格)。

嘗試更換你的代碼如下:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [self.table dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) 
    { 
     cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; 
    } 

    [self updateCell:cell withInfo:[self.search objectAtIndex:indexPath.row]]; 
    return cell; 
} 

-(void)updateCell:(UITableViewCell *)cell withInfo:(NSDictionary *)info{ 
    //set image for cell 
    //set text for cell.textlabel 
    //set text for cell.detailTextLabel 
    //create an UIButton and add to cell.content view 
} 
+0

另外,你需要'autorelease'的原因是因爲每個'init *'都必須與一個發行版配對,但是由於在你返回它之後你不能釋放這個單元格,你可以通過調用'autorelease'。 – Lance