以下陈述有什么问题?
- (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;
}
为什么在分析此代码时会出现“未定义或垃圾值返回给调用者”的逻辑错误?
答案 0 :(得分:11)
将NSString * title设置为nil:NSString * title = nil;
if(section既不是0也不是1)然后switch(section)经历默认值:然后它返回title;这只是指针指向任何东西或未初始化的指针。
所以将标题字符串赋给nil;你宣布它的地方。
- (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 :(得分:2)
因为当section
不是1
或2
时,title
未初始化。您可以在第一行或default
语句的switch
情况下初始化它。