2011-11-07 26 views
2

以下語句有什麼問題?邏輯錯誤「未定義或垃圾值返回給調用者」

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    NSString *title; 

    switch (section) 
    { 
     case 0: 
      title = @"Section 1"; 
      break; 
     case 1: 
      title = @"Section 2"; 
      break; 
     default: 
      break; 
    } 

    return title; 
} 

爲什麼在分析此代碼時出現邏輯錯誤「Undefined or garbage value returned to caller」?

回答

11

設置NSString *標題到零:NSString * title = nil; 如果(節不是0也不是1),則switch(節)通過默認值:然後它返回標題;這只是指向沒有或未初始化的指針。 因此,分配標題字符串爲零;你在哪裏宣佈它。

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    NSString *title = nil; 

    switch (section) 
    { 
     case 0: 
      title = @"Section 1"; 
      break; 
     case 1: 
      title = @"Section 2"; 
      break; 
     default: 
      break; 
    } 

    return title; 
} 
+1

設置並返回int時,這也適用於heightForRowAtIndexPath。所以「int cellHeight;」將需要是「int cellHeight = 0;」類似於這個NSString的情況。 – whyoz

2

因爲當section不是12title是未初始化。您可以在第一行或switch聲明的default案例中初始化它。