0

i have this code in my .h:

@property (nonatomic, retain) NSArray *arrayData;

What is the difference between:

self.arrayData = [[NSArray alloc]initWithObjects:@"date",@"trip",nil];

and:

arrayData = [[NSArray alloc]initWithObjects:@"date",@"trip",nil];

and what should i use and how to release the arrayData variable.

Thanks

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
Gerardo
  • 5,800
  • 11
  • 66
  • 94

1 Answers1

1

The difference is that using self.arrayData = ... retains the array. You should release it using self.arrayData = nil;.

The code you have had here doesn't work, for init alone doesn't allocate an array. You could use

self.arrayData = [NSArray arrayWithObjects:@"date",@"trip",nil];

To allocate and initialize the array.

ps the arrayWithObjects returns an allocated and autoreleased object. That means that the object will vanish if you don't retain it. So use self.arrayData = ... to do so.

The equivalent with alloc/init/autorelease would read:

self.arrayData = [[[NSArray alloc] initWithObjects:....,nil] autorelease];
mvds
  • 45,755
  • 8
  • 102
  • 111
  • [[NSArray alloc]initWithObjects:@"date",@"trip",nil]; most certainly does allocate an array. – Stefan H Jan 11 '11 at 23:45
  • @StefanH: someone decided to edit and fix the original question. ;-) – mvds Jan 11 '11 at 23:46
  • but when i use this: arrayData = [[NSArray alloc]initWithObjects:@"date",@"trip",nil]; since i called alloc i have the ownership of the object, haven't i? So i need to release it too. I don't understand the difference sorry – Gerardo Jan 11 '11 at 23:47
  • Yes, correct. That is a perfectly valid way. **But** if you do that again, the original object will not be deallocated (unless you would actively call `[arrayData release]`). If you use `self.arrayData = ...` twice, the first object *will* be deallocated without you doing that explicitly. That's the difference. – mvds Jan 11 '11 at 23:50
  • and a last question. If a need and empty array, is this is correct? self.dataSource = [[[NSMutableArray alloc] init] autorelease]; thanks – Gerardo Jan 12 '11 at 00:15
  • 10 out of 10 points! For the bonus point, use `initWithCapacity:` to tell beforehand how much room you need. – mvds Jan 12 '11 at 00:27
  • @xger86x yes, it's correct. however, it is more common to use the convenience constructor: `self.dataSource = [NSMutableArray array];` in this specific case. you'll still use alloc+init+autorelease when a convenience constructor does not exist for a particular type. – justin Jan 12 '11 at 00:52