Reputation: 898
i need clarification for memory management concepts.
i declare one variable in .h
@interface RootViewController : UIViewController
{
NSMutableArray *objMutableArray;
}
@property (nonatomic,retain) NSMutableArray *objMutableArray;
in .m file
@implementation RootViewController
@synthesize objMutableArray=_objMutableArray;
- (void)viewDidload
{
[super viewDidload];
self.objMutableArray=[[NSMutableArray alloc]init];
[self.objMutableArray addObject:@"FirstRow"];
[self.objMutableArray addObject:@"SecondRow"];
[self.objMutableArray addObject:@"ThirdRow"];
[self.objMutableArray addObject:@"FourthRow"];
[self.objMutableArray addObject:@"FifthRow"];
}
i used self.objMutableArray all places. but when i release memory for that instance i used _objMutableArray.
- (void)dealloc
{
[_objMutableArray release];
[super dealloc];
}
actually i confused when i release memory for that instance. please tell me i did correct or i must release "objMutableArray" object.
Upvotes: 3
Views: 719
Reputation: 2017
Shouldn't this viewDidUnload
be viewDidLoad
. Since you have written @synthesize objMutableArray=_objMutableArray;
, so from there on if you want to access this property directly without making use of setters and getters. You will have to use _objMutableArray
. That line in dealloc [_objMutableArray release];
will decrease the objects retain count by one, such that if the resultant retain count is 0, the the object will be released.
Upvotes: 0
Reputation:
You seem to be using manual memory management and not ARC. Which is fine, but you got it wrong.
please tell me i did correct or i must release "objMutableArray" object.
Of course you have to release it because you created it using alloc
. But how you did it is not correct. You are leaking memory because in the viewDidUnload
method (I suppose that should be viewDidLoad
instead, shouldn't it!?) you are assigning to a retain
property - your object will have a reference count of two (one because of + alloc
, one because of (retain)
).
Now when you are releasing it in - dealloc
, it will still have a reference count of one, so your class doesn't dispose of its ownership, hence the memory leak.
Solution:
You can use either the property or the instance variable. Don't mix the two. Approach #1:
_objMutableArray = [[NSMutableArray alloc] init];
// ...
[_objMutableArray release];
Approach #2:
self.objMutableArray = [[[NSMutableArray alloc] init] autorelease];
// ...
self.objMutableArray = nil;
Upvotes: 2
Reputation: 34296
Going through your code
- (void)viewDidLoad
{
[super viewDidLoad];
self.objMutableArray=[[NSMutableArray alloc]init];
......
......
}
Use
self.objMutableArray = [NSMutableArray array];
instead of
self.objMutableArray=[[NSMutableArray alloc]init];
I think this question is already answered.
Upvotes: 0