user4764267
user4764267

Reputation:

NSMutableArray not being populated

The code for my UITableView is not being red, which can only meen my array is not being populated. I am using a core-database and as I can see from the print i get it shows that my DB has the data in it. It is just not being displayed. Here is my code:

 - (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:nil];

    [self reloadArray];

}
-(void) reloadArray
{

    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    NSManagedObjectContext *context = [delegate managedObjectContext];

    NSFetchRequest *fetch = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Project" inManagedObjectContext:context];
    [fetch setEntity:entity];
    NSManagedObject *object = nil;
    NSError *error;
    NSArray *result = [context executeFetchRequest:fetch error:&error];

    for (int i = 0; i <  [result count]; i ++) {
        object = [result objectAtIndex:i];
        [_projectArray addObject:[object valueForKey:@"name"]];
    }



}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    [self reloadArray];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [_projectArray count];

}


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

    static NSString *cellID = @"TableCell";
    NSManagedObject *object = [self.projectArray objectAtIndex:indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];

    tableView.delegate = self;
    tableView.dataSource = self;
    cell.textLabel.text = [_projectArray objectAtIndex: indexPath.row];
    return cell; 
}

Upvotes: 1

Views: 61

Answers (1)

rebello95
rebello95

Reputation: 8576

You're setting your delegate and dataSource in tableView: cellForRowAtIndexPath:. These need to be set when setting up the table view initially, not when a delegate method is being called (because that method will never get called).

To re-iterate, set your delegate and dataSource properties in viewWillAppear:animated: or viewDidLoad:

- (void)viewDidLoad {

    tableView.delegate = self;
    tableView.dataSource = self;
}

Failing to set these before calling reloadData will result in none of your delegate or dataSource methods being called.

Upvotes: 2

Related Questions