Please see following code I want to know how can I de-alloc cell . From what I have understood there must be a de-alloc for every alloc and release for every retain.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"UITableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle: UITableViewCellStyleSubtitle
reuseIdentifier: CellIdentifier] autorelease];
}
cell.textLabel.text = [dataArray objectAtIndex:indexPath.row]; return cell;
}
and from the code below am I doing the right thing to de-alloc the dataArray or should it be release or both.
Interface
@interface myViewController : UIViewController
{
NSArray *dataArray;
}
@property(retain,nonatomic) NSArray *dataArray;
@end
From Implementation
- (void)viewDidLoad
{
[super viewDidLoad];
self.dataArray=[[NSArray alloc] initWithObjects:@"XXX",@"YYY",@"ZZZ",nil];
}
- (void)viewDidUnload
{
[super viewDidUnload];
[self.dataArray dealloc];
}
In your example, the cell you allocated will be autoreleased because you have sent the object the autorelease message. So you don’t need to worry about its memory being freed – that will happen automatically.
As to your second question, in general, you should not call dealloc directly. The system calls dealloc for you when an object’s retain count goes to zero. You should read the following article which does a good job of explaining memory management in a very clear way: http://interfacelab.com/objective-c-memory-management-for-lazy-people/.
The specific code you posted has two problems. First, based on what I said above, the dealloc should be replaced with a call to release. Second, you actually have a memory leak: when you alloc the dataArray object, it gets a retain count of 1. But you assign it to a property defined with the “retain” attribute. So the setter for that property will retain the object again, taking its retain count to 2. When you finally release, it will go back down to 1, but not to zero, so it won’t be released.
To fix this, instead of assigning the alloc’d object to the property, assign it to the instance variable backing the property. By default, the instance variable will have the same name as the property, so you just do
If you explicitly gave the instance variable a name when you synthesized the property (by doing something like
@synthesize dataArray = _dataArray, then use that name.Another option you have is to not alloc/init the array but rather to use the arrayWithObjects class method on NSArray. The object you get back from that will be autoreleased, so you don’t have to worry about managing it.