@try @catch阻止在iOS 6上工作但在iOS 5上没有

133*_*ode -1 iphone try-catch ipad ios

我有一个在单元格中有2个子视图的tableview(带标签的小缩略图),如果没有任何内容可以加载(当只有第一个子视图有加载的图像和标题时)我想要隐藏第二个子视图.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *reuse = @"reuse";
    ContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:[Utils buildNibNameFromPrefix:@"ContentTableViewCell"] owner:self options:nil] objectAtIndex:0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    cell.cellIndex = indexPath.row;

    NSUInteger selectedIndex = [Utils getIndexForContentTitle:[Utils getContentBookmark]];
    NSUInteger titleIndex = indexPath.row * self.noOfContentPerCell;
    NSUInteger cellIndex = NSNotFound;
    for (int i = 0; i < self.noOfContentPerCell; i++) {
        @try {
            if (titleIndex == selectedIndex) {
                cellIndex = i;
            }

            NSArray *content;
            if ([[NSUserDefaults standardUserDefaults] boolForKey:@"unlock"] == NO) {
                content = CONTENT_INDEXS;
            }
            else {
                content = CONTENT_INDEXS_UNLOCKED;
            }

            NSString *title = [content objectAtIndex:titleIndex];
            [cell setTitle:title forContentAtIndex:i];

            NSString *thumbnail;

            if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
            {
                thumbnail = [NSString stringWithFormat:@"%@-iphone-thumbnail.jpg", title];
            }
            else
            {
                thumbnail = [NSString stringWithFormat:@"%@-ipad-thumbnail.jpg", title];
            }

            [cell setImageNamed:thumbnail atIndex:i];

            [cell showContainerAtIndex:i];
        }
        @catch (NSException *exception) {
            [cell hideContainerAtIndex:i];
        }
        titleIndex++;
    }

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

它可以在iOS 6上运行,如果没有要加载的内容,@ catch会隐藏这个子视图,但是在iOS 5崩溃发生在:

NSString *title = [content objectAtIndex:titleIndex];
Run Code Online (Sandbox Code Playgroud)

LJ *_*son 7

这看起来很傻.
- Try/Catch除非没有别的办法,否则我常常讨厌.
- 为什么不检查index该集合上是否存在.
- 换句话说,不是看是否会有,而是error检查导致和处理的条件error.

  • @ 1337你基本上使用Try/Catch代替单个`if`语句; 那是非常低效的.在使用它来访问对象之前,只需检查以确保索引不超出数组的范围.使用Try/Catch就像使用`GOTO`语句乱丢C代码来替换`break`和`else`.它没有多大意义.如果您使用了`if`语句,那么您现在可能根本不会遇到此问题. (4认同)