user698200
user698200

Reputation: 399

contentsOfDirectoryAtPath crashes

I want to list files in the directory in table view of navigation control. It shows files in the directory. But whenever I scroll down, my simulator crashes. What is the problem? dirArray is defined in .h file as NSArray *dirArray.

- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *path = [[NSFileManager defaultManager]currentDirectoryPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    dirArray = [fileManager contentsOfDirectoryAtPath:path error:nil];      
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:   (NSInteger)section {
    return [dirArray count];
}

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

    static NSString *CellIdentifier = @"Cell";    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
    reuseIdentifier:CellIdentifier] autorelease];
    }
    NSString *fileName = [dirArray objectAtIndex:indexPath.row];
    cell.textLabel.text = fileName;

    return cell;
}

Upvotes: 0

Views: 1642

Answers (2)

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

Your problem is that

dirArray = [fileManager contentsOfDirectoryAtPath:path error:nil];

will have dirArray pointing to an autoreleased object. So by the time you are accessing it later, it is being deallocated. Either retain it.

dirArray = [[fileManager contentsOfDirectoryAtPath:path error:nil] retain];

Or much better, declare it as a property and do

self.dirArray = [fileManager contentsOfDirectoryAtPath:path error:nil];

Upvotes: 2

Rakesh Bhatt
Rakesh Bhatt

Reputation: 4606

you should make property of the your array and @synthesize it.

or

you shold alloc array and relese it in the dealloc.

Upvotes: 0

Related Questions