How to check if a structure has been initialized?

I use NSRange (struct) and initialize it as follows:

@interface MyViewController : UIViewController { NSRange currentRange; } 

NSRange has a field of location and length.

How to check if a structure with a value has been initialized? I tried:

 if (myRange.length == nil) 

but the compiler complained about comparing a pointer to an integer. Thanks.

+4
source share
4 answers

nil is a pointer, but length is an integer, so a warning to the compiler. You can compare length to 0 , but then this is a legitimate value for length in NSRange . If I needed a “not yet initialized” value for currentRange , I would decide to set it:

 { .location = NSNotFound, .length = 0 } 

at -init . This, of course, suggests that a range can never accept this value during operations. If a range can really take any values ​​in its domain, then you cannot use any of them as a placeholder for "not yet initialized".

You can choose to keep a pointer to a range that is NULL until the range is set. Another option would be to use a state template to distinguish between states before and after the range is set. Another is the development of the class and its interface, so that the range is only ever used after its installation.

+9
source

You can not. If it is not initialized, it will have random values ​​or be initialized to zero, depending on the compiler, so there is no reliable way to check.

0
source

You basically have two options: either initialize the structure explicitly (a suggestion for initializing the location for NSNotFound is a good one), or make it a pointer. But then you will manage the heap memory for this, which is most likely more than you expected.

Philosophically, making any comparison before initialization, begs for trouble. Even if it was a pointer, I still (personally) explicitly initialized it to zero. Is there a reason you don't have a bite in an apple during the -init method for MyViewController?

0
source

One possible solution is to store somewhere a canonical initialized instance of this structure and compare with it. You still have a problem that you really should not do anything with uninitialized memory other than initialization.

0
source

All Articles