Under the hood, Objective-C objects are basically C structs. Each one contains a field called isa
, which is a pointer to the class that the object is an instance of (that's how the object and Objective-C runtime knows what kind of object it is).
Regarding the initialization of variables: in Objective-C, instance variables are automatically initialized to 0
(for C types like int
) or nil
(for Objective-C objects). Google's guidelines say that initializing your ivars to those values in your init
methods is redundant, so don't do it. For example, say you had a class like this:
@interface MyClass : NSObject
{
int myInt;
double myDouble;
MyOtherClass *myObj;
}
@end
Writing your init
method this way would be redundant, since those ivars will be initialized to 0
or nil
anyway:
@implementation MyClass
- (id)init
{
if ((self = [super init])) {
myInt = 0;
myDouble = 0.0;
myObj = nil;
}
return self;
}
@end
You can do this instead:
@implementation MyClass
- (id)init
{
return [super init];
}
@end
Of course, if you want the ivars to be initialized to values other than 0
or nil
, you should still initialize them:
@implementation MyClass
- (id)init
{
if ((self = [super init])) {
myInit = 10;
myDouble = 100.0;
myObj = [[MyOtherClass alloc] init];
}
return self;
}
@end