- The default value of the variables at the time of the announcement is -

I was wondering what are the default values ​​for variables before I initialized them ...

For example, if:

//myClass.h BOOL myBOOL; // default value ? NSArray *myArray; // default value ? NSUInteger myInteger; // default value ? 

Here are some more examples:

 //myClass.m // myArray is not initialized, only declared in .h file if ([myArray count] == 0) { // TRUE or FALSE ? // do whatever } 

More generally, what comes back when I do:

 [myObjectOnlyDeclaredAndNotInitialized myCustomFunction]; 

Thank you for your responses.

Gauthier.

+4
source share
3 answers

The answer is that it depends on the area in which the variable is defined.

Objective-C object instance variables are always initialized to 0 / nil / false, since the allocated memory is nullified.

Global variables are probably initialized to 0 / nil / false, because when memory is first assigned to a process, it is also reset by the operating system. However, of course, I never rely on this and always initialize them myself.

Local variables are not initialized and will contain random data depending on how the stack has grown / shrunk.

NB for pointers to Objective-C objects, you can safely send messages to zero. For example:

 NSArray* foo = nil; NSLog(@"%@ count = %d", foo, [foo count]); 

is completely legal and will work without fail with the output of something like:

 2010-04-14 11:54:15.226 foo[17980:a0f] (null) count = 0 
+2
source

the default value of NSArray will be nil if you did not initialize it.

0
source
 //myClass.h BOOL myBOOL; // default value ? NSArray *myArray; // default value ? NSUInteger myInteger; // default value ? 

Bool myBool, if not initialized, will receive the default value False.

NSArray * myArray, if not assigned, initialized (for example, NSArray *myArray = [[NSArray alloc] init]; ) will have a default value of NIL. if you call an account on a unified array, you will get a non-0 exception.

 //myClass.m // myArray is not initialized, only declared in .h file if ([myArray count] == 0) { => here it should crash because of [myArray count] // do whatever } 

for NSUInteger myInteger, the default value should be 0, the documentation states that this is used to describe an unsigned integer (i didn; t represents integers with this)

when you call [myObjectOnlyDeclaredAndNotInitialized myCustomFunction]; It must break, cause an exception.

hope this helps

0
source

Source: https://habr.com/ru/post/1306889/


All Articles