简体   繁体   English

有没有一种简单的方法可以在循环/重复运行的方法中仅一次(首次)分配一个值?

[英]Is there a simple way to assign a value only once(first time) inside a loop/repeatedly running method?

For example I want to set different cell height for different screen size. 例如,我想为不同的屏幕尺寸设置不同的单元格高度。 Within a UITableView data source method: 在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;
    }
}

Is there a generic mechanism to assign the defaultHeight only once and without add additional "if else"(Just wonder is there some methods I missed)? 是否有一种通用机制仅分配一次defaultHeight而不添加其他 “ if else”(只是想知道我是否错过了一些方法)? And inside the repeatedly called method to keep the code structure simple and easy to move around and don't need to bother on what time to init. 在重复调用的方法内部,可以使代码结构简单易行,并且无需费心初始化时间。

Yes, iOS provides a way to do this - use dispatch_once function, and provide a block that performs initialization: 是的,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 guarantees that the block will be executed only upon the initial pass through the function call. iOS保证仅在初次通过函数调用时才执行该块。

I think you are talking about some conditional operator. 我认为您是在谈论一些条件运算符。 Conditional operator is the simplest way which replaces long if else conditions. 有条件的经营者是它取代长的最简单的方法if else条件。 Try This! 尝试这个!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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