yosh
yosh

Reputation: 3305

iPhone - Array to UITableView

I can't display array in UITableView. The thing I do is - in viewWILLappear I'm creating array. In viewDIDappear I'm filling the array. But when I run [myArr count] or [myArr objectAtIndex:indexPath.row] in table setup I get empty table. If I define constant integer as row count and some constant string as cell text everything works fine. Is there some populate() method I have to run or is it a problem with some order of declarations?

Thanks for any help. Here's the code:

- (void)viewWillAppear:(BOOL)animated {
    myArr = [[NSMutableArray alloc] initWithCapacity:100];
}
- (void)viewDidAppear:(BOOL)animated {
    [self load_array];
}
- (void) load_array {
  for (SomeObject *someObject in SomeObjects) {             
     [myArr addObject:someObject.someString];
     NSLog(@"Value: %@", [myArr objectAtIndex:([myArr count]-1)]); // works 
  }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [myArr count]; // works if I return const ("return 2")
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (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];
    }
    cell.textLabel.text = [myArr objectAtIndex:indexPath.row]; //=@"ASDF" works.
    return cell;
}

Upvotes: 0

Views: 2060

Answers (1)

Philipp
Philipp

Reputation: 1963

You need to perform reloadData on your table view to make the view re-load the table cells.

Update: You should not allocate your array in the viewWillAppear, as this method might be called several times. Construct the array in the viewDidload: and fill it there, or in a background thread, or in the viewWillAppear: (using a conditional statement to check if its already filled). You should also make sure that you do not create a memory leak, from the code you provided it is likely that myArr will be replaced by a newly allocated array without being released.

Upvotes: 2

Related Questions