SEG
SEG

Reputation: 1715

objective c memory leak with array?

In my application i declare an array property,

@property (nonatomic, retain) NSArray *listOfItems;

and in my viewDidLoad method,

listOfItems = [[NSArray alloc] initWithObjects:@"First", @"Second", nil];

I do not release the array in my viewDidLoad, because the objects in the array will be required elsewhere in the application.
Finally in my dealloc method i put,

[listOfItems release];

My question is: Is there a memory leak in this code? The retain count should be increased twice due to the (retain) in the property as well as the alloc in the viewDidLoad, but only decreased once in the dealloc method.

Upvotes: 1

Views: 251

Answers (6)

Mahesh
Mahesh

Reputation: 662

It wont be confusing if you practice like this

@property (nonatomic, retain) NSArray *listOfItems;  
NSArray *temparray = [[NSArray alloc] initWithObjects:@"First", @"Second", nil];  
self.listOfItems = temparray;  
[temparray release];

and in dealloc

[listOfItems release];

Upvotes: 0

Caleb
Caleb

Reputation: 124997

Yes, there's a potential leak. Consider:

  1. In -viewDidLoad, you set up listOfItems as you've described.
  2. Subsequently, some other code calls yourObject.listOfItems = someNewList;.
  3. Your -dealloc releases listOfItems.

I realize that #2 above probably doesn't happen in your code, but a month from now you may decide that you need to update the list for some reason and introduce this problem. Think about what happens if #2 ever does occur...

  • Your listOfItems ivar suddenly points to a different list.
  • You no longer have a reference to the old list, so it can never be released. That's your leak.

It's much better to release the array in -viewDidLoad after you've assigned it to your property.

Upvotes: 0

Chanok
Chanok

Reputation: 800

Just like @MiRAGe said,

listOfItems = [[NSArray alloc] initWithObjects:@"First", @"Second", nil];

The retain count will be 1

but if the code is

self.listOfItems = [[NSArray alloc] initWithObjects:@"First", @"Second", nil];

The retain count will be 2

Upvotes: 0

Jake
Jake

Reputation: 3973

the retain will only 'kick in' when you do it like this

self.listOfItems = [[NSArray alloc] initWithObjects:...];

Now, the retain count is indeed 2. If you leave self out, it will just be one. There is a distinct difference in calling 'set' and just assigning.

To answer your original question; your code is not leaking.

Upvotes: 1

SriPriya
SriPriya

Reputation: 1240

NSArray *array=[[NSArray alloc] initWithObjects:@"First",@"Second",nil];
self.listOfItems=array;
[array release];

You, can use this way also.

Upvotes: 0

cem
cem

Reputation: 3321

Since your setter retains the array, you must release it, after you allocated and set it in your viewDidLoad method (with this notation I suggest "autorelease").

But perhaps it's easier for you, if you use [NSArray arrayWitObjects:].

Upvotes: 0

Related Questions