I would like to know the meaning of the below written lines with an example. I'm unable to understand what the lines actually mean. The lines are from google's objective-c coding guidelines.
Initialization
Don't initialize variables to 0 or nil in the init method; it's redundant.All memory for a newly allocated object is initialized to 0 (except for isa), so don't clutter up the init method by re-initializing variables to 0 or nil.
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). Apple'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
When objects are allocated by the Objective-C runtime, all the memory where instance variables reside is zeroed out for you, so there is no need to set instance variables to 0 or nil
. You can set them to any value you want. Some developers even ignore the redundancy and set instance variables to 0 anyway just for explicitness or descriptive purposes.
isa
means “is a”. Every Objective-C object (including every class) has an isa
pointer. The runtime follows this pointer to determine what class an object is, so it knows what selectors the object responds to, what its super class is, what properties the object has, and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With