- Default value of variables at the time of declaration -

孤人 提交于 2019-12-05 14:39:18

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!