逻辑错误“未定义或垃圾值返回给调用者”

时间:2011-11-07 19:36:07

标签: objective-c ios

以下陈述有什么问题?

- (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;
}

为什么在分析此代码时会出现“未定义或垃圾值返回给调用者”的逻辑错误?

2 个答案:

答案 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不是12时,title未初始化。您可以在第一行或default语句的switch情况下初始化它。