Default value of an Objective-C struct and how to test

后端 未结 7 1113
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-31 15:33

I\'m trying to test if a property has been set yet. I know that with objects that I\'ve got:

CGRect ppGoalFrame;
LocalPlaySetup *localPlaySetup;
<
相关标签:
7条回答
  • 2021-01-31 15:52

    I don't think you can do a binary comparison of a C structure, which is what CGRect is. A quick Google search and checking the C For Dummies Desk Reference didn't turn anything up. You could declare CGRect ppGoalFrame, initialize the members of the structure with default values (if they're not already), and test the structure members.

    Update Edit: This question has been asked for C structures.

    0 讨论(0)
  • 2021-01-31 15:58

    Only pointers can be null. CGRect is a struct - it represents a contiguous block of memory. The only way to tell if it has been set it to check its contents.

    Apple does provide a constant CGRectNull. You could set your variable to this and use the CGRectIsNull function to determine if it has been set. CGRectNull is not the same as CGRectZero so you need not worry if the desired value is zero.

    Note that CGRectNull simply contains a CGRect struct filled with values that Apple can later identify for the CGRectIsNull function. It is not the same null as when comparing pointers.

    0 讨论(0)
  • 2021-01-31 16:01

    Actually there is an obvious and elegant solution (lol):

    SomeStruct someStruct = {0};

    Which just fills all the "elements" of the struct with zeroes.

    0 讨论(0)
  • 2021-01-31 16:06

    You can wrap CGRect in NSValue too:

    [NSValue valueWithCGRect:CGRectMake(x, y, width, height)]

    And then avoid the nil value.

    0 讨论(0)
  • 2021-01-31 16:09

    From CGGeometry.h:

    /* Return true if `rect' is empty (that is, if it has zero width or height),
       false otherwise. A null rect is defined to be empty. */
    

    an empty rectangle is one that has no area, where on or both sides are zero.
    Use instead:

    CGRect newRect = CGRectNull;
    
    0 讨论(0)
  • 2021-01-31 16:12

    There is no universal "nothing" value. There's nil for objects and NULL for pointers, but there's no equivalent for plain value types — they always have some value, even if it's just nonsense. You can take an arbitrary value and say "I'm going to call this the null value for this type" (say, #define IntNull 4444444 and hope some calculation never accidentally returns that value), but there's no real null value.

    In the case of CGRect in particular, Apple used the "pick an arbitrary value" tactic and defined CGRectNull, but CGRect variables aren't set to that by default — you have to specifically set it yourself. By default, CGRect instance variables are set to CGRectZero, but remember that this is just a normal CGRect struct at location (0,0) with 0 width and 0 height. And local CGRects in a function have a totally unpredictable value.

    0 讨论(0)
提交回复
热议问题