views:

127

answers:

2

Hello all,

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.

+8  A: 

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
mipadi
@mipadiThanks for the answer i would like to know about this line.Don't initialize variables to 0 or nil in the init method; it's redundant. Where should we use this pattern. Does it mean that we should not initialize variable's in data Modal's
Rahul Vyas
Feel free to initialize your data -- just don't initialize your variables to `0` or `nil`.
sarnold
sarnold basically explained it, but I updated my answer to address this issue.
mipadi
@mipadi: +1, but if your `init` method only calls `[super init]` then it doesn't need to be overridden at all.
dreamlax
True, it was just to illustrate the difference.
mipadi
+1  A: 
dreamlax