简体   繁体   中英

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:

-(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)? 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:

-(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.

I think you are talking about some conditional operator. Conditional operator is the simplest way which replaces long if else conditions. Try This!

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

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