简体   繁体   中英

Logic error “Undefined or garbage value returned to caller”

What is wrong with the following statements?

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

Why do I get the logic error "Undefined or garbage value returned to caller" on analyzing this code?

set NSString * title to nil: NSString * title = nil; if(section is neither 0 nor 1 ) then switch (section) goes through default: and then it return title; which is just pointer pointing to nothing or uninitialized. So assign title string to nil; where you declared it.

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

Because when section isn't 1 or 2 , title is uninitialized. You can either initialize it in the first line or in the default case of the switch statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM