Ted
Ted

Reputation: 3885

deleting from UITableView crashes app

I have a UITableView and I implemented the delete from table swipe method.
For some reason, the assignment of arrays is causing the app to crash.
I would like to know why.

two properties:

@property (nonatomic,retain) NSMutableArray *mruItems;
@property (nonatomic,retain) NSArray *mruSearchItems;
 . 
 .
 .
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle != UITableViewCellEditingStyleDelete)
        return;

    NSString *searchString = [self.mruSearchItems objectAtIndex:indexPath.row];
    [self.mruItems removeObject:searchString];

    [self.mruSearchItems release];

    // This line crashes:
    self.mruSearchItems = [[NSArray alloc] initWithArray:self.mruItems];

    [self.searchTableView reloadData];
   }

It is as if after mruItems's objects has been removed, it can't help initialize mruSearchItems...

Thanks!

EDIT:

EXC_BAD_ACCESS

@synthesize mruItems,mruSearchItems; <--Debugger points here

Upvotes: 0

Views: 139

Answers (3)

ganesh manoj
ganesh manoj

Reputation: 977

I think your getting problem at releasing array.i hope this will help you

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{

NSString *searchString = [self.mruSearchItems objectAtIndex:indexPath.row];
 [self.mruSearchItems removeObjectAtIndex:searchString]
[self.searchTableView reloadData];

}

Upvotes: 0

KDaker
KDaker

Reputation: 5909

why do you need to release the object and reallocate it? if you make mruSearchItems an NSMutableArray then you can simply call:

[mruSearchItems removeAllObjects];
[mruSearchItems addObjectsFromArray:self.mruItems];

hope this helps

Upvotes: 1

fvwmer
fvwmer

Reputation: 301

It is double releasing causes crash.

[self.mruSearchItems release];

This makes refcount -1

self.mruSearchItems = [[NSArray alloc] initWithArray:self.mruItems];

This makes refcount -1

Since mruSearchItems has "retain" in property attributes, your assign to it will cause another refcount -1.

So either remove the release line or set it to nil after release it and before assign to it.


Edit: This line

self.mruSearchItems = [[NSArray alloc] initWithArray:self.mruItems];

causes memory leak, fix it like this:

self.mruSearchItems = [[[NSArray alloc] initWithArray:self.mruItems] autorelease];

or:

NSArray *tmpArray = [[NSArray alloc] initWithArray:self.mruItems];
self.mruSearchItems = tmpArray;
[tmpArray release];

Edit Again

What does "retain" in property actually do?

Take mruSearchItems as example, when you assign it:

- (void)setMruSearchItems:(NSArray *)newArray
{
    [newArray retain];
    [mruSearchItems release]; // this lines causes a second release to the old value
    mruSearchItems = newArray;
}

Upvotes: 3

Related Questions