NSArray mistery again

Discussion in 'iPhone/iPad Programming' started by jagatnibas, Sep 23, 2008.

  1. macrumors regular

    Joined:
    Jul 28, 2008
    #1
    Hi All,

    I have a strange problem.

    I have an interface MyInterface : UIView

    inside that I have a NSArray* arr as member variable.

    in the function initFrame

    I initialize it with [NSArray arraywithobjects:...];

    in this function when i try accessing an item using [arr objectAtIndex:0] , it runs fine and gives me proper object.

    in the function touchended:....
    if i try same [arr objectAtIndex:0] I get a crash.

    why so ?

    I have done this variable as @property and @synthesize also

    no success..

    please share any thought for solution

    regards
    Jagat
     
  2. macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
  3. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #3
    Are you actually using the accessor? If you set the variable directly the accessor is not used and it won't get retained. Always use the accessor

    So if you have a property called myProperty always use self.setMyProperty = something to set it, don't use myProperty = something.
     
  4. thread starter macrumors regular

    Joined:
    Jul 28, 2008
    #4
    Thanks

    Thanks Robbie,

    It worked, though i could not fully understand the difference between the two

    regards
    Jagat
     
  5. macrumors 6502a

    Joined:
    Nov 9, 2007
    #5
    When you do this:

    Code:
    myVar = [NSArray array];
    
    You assign an autoreleased object directly to your instance variable; it will be released some time in the near future. It won't be retained without an explicit call to retain. When you declare a property and use self.myVar:

    Code:
    // in your header file
    @property (nonatomic, retain) NSArray *myVar;
    
    // in your implementation
    @synthesize myVar;
    
    // some method
    self.myVar = [NSArray array];
    
    You are really calling [self setMyVar:[NSArray array]] which is the method generated by synthesize. If your @property is declared with retain like in the example above, the synthesized method will retain your object for you. It does something roughly like this:

    Code:
    - (void)setMyVar:(NSArray *)myNewVar;
    {
      if(![myNewVar isEqual:myVar]) {
        [myVar release];
        myVar = [myNewVar retain];
      }
    }
    
    I suggest reading the documentation on properties.
     

Share This Page