question about creating an Object

Discussion in 'iOS Programming' started by tranvutuan, Feb 6, 2012.

  1. tranvutuan
    Expand Collapse
    macrumors member

    Dec 19, 2011
    I am used to have this in my code
    @property ( strong, nonatomic ) ClassA *varA
    [COLOR="Blue"]varA  = [[ClassA alloc] init];[/COLOR]
    if ( varA isEqual:nil )
       NSLog@"var A is nil");
       NSLog@"var A is not nil");
    this is a result from console
    var A is not nil
    I thought var A should be nil then. So my question is what does blue line do and why var A is not nil after all
  2. xStep
    Expand Collapse
    macrumors 68000

    Jan 28, 2003
    Less lost in L.A.
    I suggest you read a beginners Objective-C book. Your question is extremely basic.

    The alloc method of ClassA allocates memory for an instantiated object of the class. At that point, varA, which is really just a pointer, would have a value if all you did was this line in your implementation source.
    varA = [ClassA alloc];
    The only reason varA wouldn't have a value other than zero, would be if the alloc failed.

    The init method, called against the instantiated object, is used to setup variables inside the new object. Given this information, you can follow that line above to this.
    [varA init];
    The init method could fail and return zero so it is safer to do this. There has been discussion of this fact online over the years.
    varA = [varA init];

Share This Page