views:

136

answers:

2

Hey all,

I have a UITableView that displays various nsstrings from a custom object called a "Transaction." in CellForRowAtIndexPath it the allocates a new instance of a transaction and then copies the the values from a particular transaction that lives in the delegate array so I can access it from different views. It then uses the new transaction 'copy' and it's properties to popluate the table cell. The problem I'm having is if I release the copied transaction object when I go to redisplay the table the app crashes. if I comment out the release the program runs well, but I'm worried about memory management obviously. My question is what the heck should I do, is there another place to release this?

Here is the code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"TransCell";

UITableViewCell *cell  =  [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

// Set up the cell...
NSUInteger row = [indexPath row];
CashAppDelegate *mainDelegate = [(CashAppDelegate *) [UIApplication sharedApplication] delegate];


Transaction *cellTrans = [[Transaction alloc] init];


cellTrans = [mainDelegate.transactionArray objectAtIndex:row];

NSString *string = [NSString stringWithFormat:@"$%1.2f %@ | %@", cellTrans.amount, cellTrans.category, cellTrans.descriptionString];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

cell.text = string;
//[cellTrans release];
return cell;
}
+2  A: 

You want:

Transaction *cellTrans = [mainDelegate.transactionArray objectAtIndex:row];

instead of:

Transaction *cellTrans = [[Transaction alloc] init];


cellTrans = [mainDelegate.transactionArray objectAtIndex:row];

Then you wont need the release. The problem is cellTrans is a pointer. What you've done is create a new object, point to it, then point to something else ignoring the object you just made. Then you try to get rid of the object in the array rather than the one you just made.

David Kanarek
+2  A: 

Hi nickthedude,

You don't actually need to allocate a new Transaction object seeing as you only want/need a reference to one that already exists in your delegate transaction array. So instead of:

Transaction *cellTrans = [[Transaction alloc] init];
cellTrans = [mainDelegate.transactionArray objectAtIndex:row];

and tidying up with

[cellTrans release];

just obtain a reference with this one line:

Transaction *cellTrans = (Transaction *)[mainDelegate.transactionArray objectAtIndex:row];
EddieCatflap
Thanks that worked, appreciate the help!
nickthedude