NSArray mistery again

Discussion in 'iOS Programming' started by jagatnibas, Sep 23, 2008.

  1. jagatnibas
    Expand Collapse
    macrumors regular

    Jul 28, 2008
    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

  2. robbieduncan
    Expand Collapse
    Moderator emeritus


    Jul 24, 2002
    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.
  3. jagatnibas
    Expand Collapse
    thread starter macrumors regular

    Jul 28, 2008

    Thanks Robbie,

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

  4. Luke Redpath
    Expand Collapse
    macrumors 6502a

    Nov 9, 2007
    Colchester, UK
    When you do this:

    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:

    // 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:

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

Share This Page