How to check if CGSize is initialized (or its value is different from "nil")

I have a CGSize property in the class and I need to check if it has been initialized. I know that CGSize is not an object, but, generally speaking, this is the same idea of ​​checking whether an object is different from nil. How to do it?

+6
source share
3 answers

It depends on what you mean by "in class". If it is an instance variable, your problems are over because you are guaranteed that the instance variable will be automatically initialized to some form of zero (i.e. CGSizeZero ). But if you just mean "in my code somewhere", for example. automatic variable, then there is no such test; it is entirely up to you to initialize before use, and as long as you do, the value can be anything at all (sorry, but this is how C works).

All in all, your question in itself is a "bad smell." If it matters to you at some point in your code whether this value has been initialized, you are doing it wrong. This is your value; you needed to initialize it (for example, when your shared object was initialized). Or, if for some reason you need to know if your setter has ever been called, you need to add a boolean to your setter, which tells you if it was ever called.

+8
source

You can compare it with CGSizeZero or an arbitrary size that is considered invalid.

 if (!CGSizeEqualToSize(CGSizeZero, mySize) { // do something } 
+13
source

CGSize is a C structure. With some exceptions (when used as iVar), there is no guarantee that it will be initialized. It can be anything, especially when created on the stack.

Thus, you are responsible for correctly initializing it, and since “zeros” are valid values, there is no guaranteed way to determine if it was set to “zero” or if it was not initialized.

+2
source

All Articles