Reputation: 1715
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
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
Reputation: 124997
Yes, there's a potential leak. Consider:
yourObject.listOfItems = someNewList;
.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...
It's much better to release the array in -viewDidLoad after you've assigned it to your property.
Upvotes: 0
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
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
Reputation: 1240
NSArray *array=[[NSArray alloc] initWithObjects:@"First",@"Second",nil];
self.listOfItems=array;
[array release];
You, can use this way also.
Upvotes: 0
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