简体   繁体   中英

How to return a nil CGFloat?

I'd like to return nil to tableView:heightForFooterInSection: but that's not allowed. Is there a way to return nil as a CGFloat?

Why are you doing this?
I'm testing how a tableView will behave with a mix of Titles and Views as sectionFooters. For one footer I need to use a custom view, but for another footer I have 3 or 4 sentences of text and I like how the system styles it and sizes the footer to fit. But as soon as I implement heightForFooterInSection (which is required by viewForFooterInSection ), the footer with the title no longer auto-resizes to fit the given text. I'm trying to avoid building a custom view for the straight text.

There's no such thing as nil for primitive values. You could try returning 0.0f , but I don't know how UITableView responds to that. It may just hide the view entirely. Presumably if you want to return a custom view for one footer, you need to return a custom view for all footers.

As mentioned by others, there is no such thing as a nil for floats.

However, the Department of Ugly Hacks brings you: The NaN - "NaN" being a special reserved value of the float bit pattern representing "Not a Number".

No clue what a UITableView will make of a NaN, but in other situations it can be a way to specify that a float variable does not have a value.

If you won't tell anyone where you got the idea, here is the code:

CGFloat myNan = nanf(NULL);

Short answer: no.

Long answer: 'nil' is a pointer to nothing, used in place of a pointer to an object. CGFloat is a scalar datatype, not an Objective-C class, and is not generally used with pointers (or it would be CGFloat *).

I am late for the party but this may be useful to someone.

Like others said, you cannot return nil to primitives but you can do one of two things, to differentiate a non-set value from a set one.

  1. Use NSNotFound

     - (CGFloat)calculateHeight { // calculate height... if (heightInvalid) return NSNotFound; else return validFloatValue; } 

NSNotFound is a huge number defined by Apple and used by them on some operations. Then you can check for that, like:

if ([self calculateHeight] == NSNotFound) ... 
  1. Use NSNumber

Instead of returning a CGFloat make your function return a NSNumber .

      - (NSNumber *)calculateHeight {
         // calculate height...

         if (heightInvalid) return nil;
         else return @(validFloatValue);

      }

Then, you can return nil.

When receiving the value you do:

NSNumber *myHeightNumber = [self calculateHeight];
if (!myHeightNumber) NSLog(@"height is invalid... do something");
else myHeight = [myHeightNumber floatValue];

I hope that helps.

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