有一种简单的方法在循环/重复运行方法中只分配一次(第一次)值吗?

时间:2014-12-31 03:50:19

标签: ios objective-c

例如,我想为不同的屏幕尺寸设置不同的单元格高度。在UITableView数据源方法中:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    defaultHeight = self.view.frame.size.height > 480 ? 38 : 32;
    // how to let something like the right side of the = run just once?

    if (indexPath.row == 0) {// no need to remove.
        ...// do something 
        return 20;
    }else {
        ...// do something else 
        return defaultHeight;
    }
}

是否有通用机制只分配defaultHeight一次而不添加其他" if else"(只是想知道我错过了一些方法)?并且在反复调用的方法中,保持代码结构简单易行,不需要在什么时候初始化。

2 个答案:

答案 0 :(得分:0)

是的,iOS提供了一种方法 - 使用dispatch_once函数,并提供一个执行初始化的块:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        defaultHeight = self.view.frame.size.height > 480 ? 38 : 32;
    });
    return indexPath.row == 0 ? 20 : defaultHeight;
}

iOS保证只有在初始通过函数调用时才会执行该块。

答案 1 :(得分:0)

我认为你在谈论一些条件运算符。条件运算符是替换长if else条件的最简单方法。试试吧!

 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
     return (!indexPath.row)?20:(self.view.frame.size.height > 480)? 38 : 32;
    }