Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

jagatnibas

macrumors regular
Original poster
Jul 28, 2008
126
0
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
 

robbieduncan

Moderator emeritus
Jul 24, 2002
25,611
893
Harrogate
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.
 

jagatnibas

macrumors regular
Original poster
Jul 28, 2008
126
0
Thanks

Thanks Robbie,

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

regards
Jagat
 

Luke Redpath

macrumors 6502a
Nov 9, 2007
733
6
Colchester, UK
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.