question about creating an Object

Discussion in 'iPhone/iPad Programming' started by tranvutuan, Feb 6, 2012.

  1. macrumors member

    Joined:
    Dec 19, 2011
    #1
    I am used to have this in my code
    myClass.h
    Code:
    @property ( strong, nonatomic ) ClassA *varA
    myClass.m
    Code:
    [COLOR="Blue"]varA  = [[ClassA alloc] init];[/COLOR]
    if ( varA isEqual:nil )
       NSLog@"var A is nil");
    else
       NSLog@"var A is not nil");
    this is a result from console
    Code:
    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. macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #2
    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.
    Code:
    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.
    Code:
    [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.
    Code:
    varA = [varA init];
     

Share This Page