View Full Version : NSArray mistery again

Sep 23, 2008, 01:56 PM
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


Sep 23, 2008, 02:25 PM
Read about autoreleased objects here


and here


Sep 23, 2008, 02:33 PM
I have done this variable as @property and @synthesize also

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.

Sep 29, 2008, 01:30 AM
Thanks Robbie,

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


Luke Redpath
Sep 29, 2008, 04:06 AM
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.