Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Objective-C guarantee the initialization of interface member data?

Tags:

objective-c

In an interface such as this:

@interface MyClass : NSObject
{
    bool PlainOldBool;
}

@end

... does PlainOldBool get auto-initialized to false, or is it necessary to use an init method to do that explicitly?

like image 458
Stabledog Avatar asked Mar 28 '10 14:03

Stabledog


2 Answers

Yes (unless your false is not 0). The default +alloc/+allocWithZone: method will automatically zero out all ivars.

From https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW17

  • It initializes all other instance variables to zero (or to the equivalent type for zero, such as nil, NULL, and 0.0).
like image 131
kennytm Avatar answered May 24 '23 15:05

kennytm


Also worth noting is that if you're doing Objective-C++, C++ objects that are ivars of Objective-C objects are not initalized : their constructors are not called by default.

like image 35
n-b Avatar answered May 24 '23 13:05

n-b