Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ObjectiveC, are pointers that are class instance variables initialised to 'nil', or otherwise?

Tags:

objective-c

I.e., does ObjectiveC behave like C, in that if you create a pointer eg:

NSString* c;

Does c point to nil, or to the random value in the memory area that was reserved for it?

In other words, do pointers get pre-initialized, or do I need to do that myself? As I said, I'm aware this is not the case in C/C++, but I'm wondering if there's some ObjC magic here or not.

like image 268
Alex Taylor Avatar asked Jun 15 '09 22:06

Alex Taylor


People also ask

Are instance variables initialized?

Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

Can instance variables be used without initialization?

If you declare a final variable later on you cannot modify or, assign values to it. Moreover, like instance variables, final variables will not be initialized with default values. Therefore, it is mandatory to initialize final variables once you declare them.

Do instance variables have to be initialized in Java?

An instance variable does not compulsory need to be initialized. Instance variables are accessible inside the same class that declares them.

What does @() do OBJC?

In Objective-C, any character , numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals.


2 Answers

Class instances variables in Objective-C are guaranteed to be initialized to their empty value (0, nil, etc ...)

like image 57
JaredPar Avatar answered Oct 14 '22 08:10

JaredPar


Class instance variables and static/global variables get initialized to nil/NULL/0/false as appropriate.

However local variables are not initialized.

like image 39
Peter N Lewis Avatar answered Oct 14 '22 08:10

Peter N Lewis