I was wondering what were the default values of variables before I initialized them...
For example, if I do :
//myClass.h
BOOL myBOOL; // default value ?
NSArray *myArray; // default value ?
NSUInteger myInteger; // default value ?
Some more examples here :
//myClass.m
// myArray is not initialized, only declared in .h file
if ([myArray count] == 0) { // TRUE or FALSE ?
// do whatever
}
More generally, what is returned when I do :
[myObjectOnlyDeclaredAndNotInitialized myCustomFunction];
Thank you for your answers.
Gotye.
The answer is that it depends on the scope in which the variable is defined.
Instance variables of Objective-C objects are always initialised to 0/nil/false because the memory allocated is zeroed.
Global variables are probably initialised to 0/nil/false to because when memory is first allocated to a process, it is also zeroed by the operating system. However, as a matter of course, I never rely on that and always initialise them myself.
Local variables are uninitialised 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 nil. So, for instance:
NSArray* foo = nil;
NSLog(@"%@ count = %d", foo, [foo count]);
is perfectly legal and will run without crashing with output something like:
2010-04-14 11:54:15.226 foo[17980:a0f] (null) count = 0
by default NSArray value will be nil , if you would not initialize it.
//myClass.h
BOOL myBOOL; // default value ?
NSArray *myArray; // default value ?
NSUInteger myInteger; // default value ?
the Bool myBool if not initialized will receive the default value of False.
NSArray *myArray if not allocated,initialized(for example NSArray *myArray = [[NSArray alloc] init];
) will have the default value of NIL. if you call count on an unitialized array you will receive an exception not 0.
//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 the NSUInteger myInteger the default value should be 0, the documentation says that this is used to describe an unsigned integer(i didn;t represent integers with this one though)
when you call [myObjectOnlyDeclaredAndNotInitialized myCustomFunction];
it should break, throw an exception.
hope it helps
来源:https://stackoverflow.com/questions/2635677/default-value-of-variables-at-the-time-of-declaration