How do I use a NSMutableArray as a DataSource for my UITableView

14.4k Views Asked by At

I have an NSMutableArray in with data (hard coded).

I implemented these two TableView methods and in IB, I've set the delegate and datasource

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];

    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"] autorelease];
    }

    cell.textLabel.text = [myArray objectAtIndex:[indexPath row]];
    NSLog(@"Cell is %@", [myArray objectAtIndex:indexPath.row]);
    return cell;
}

The data won't appear in the TableView. I've ran NSLog and I can see the data is in myArray.

I added the NSLog to the code and it appears the code never executes. The question is how is my array being created?

Here's the code

- (id)init:(NSMutableArray *)theArray
{
    [super init];
    countryTable.delegate = self;
    countryTable.dataSource = self;

    UITapGestureRecognizer * tapRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)] autorelease];
    [window addGestureRecognizer:tapRecognizer];

    myArray = [[NSMutableArray alloc] init]; 
    myArray = theArray;
    return self;
}
3

There are 3 best solutions below

0
On BEST ANSWER

Your basic code is correct, just need to have an array (which you haven't provided here), so this would be one example:

NSMutableArray *myArray = [NSMutableArray arrayWithObjects:@"One",@"Two",@"Three",nil];

And you can NSLog this: NSLog(@"Count: %i, Array: %@",[myArray count], myArray);

Output: Which should return as the cell.textLabel.text per your example

Count: 3, Array: ( "One", "Two", "Three" )

You should also make sure that you set the UITableViewDelegate and UITableViewDataSource protocols in your header.

2
On

Try this -

cell.textLabel.text = [[myArray objectAtIndex:indexPath.row] retain];
0
On

I don't know if the question is still open but I give it a try.

As I read your code I can't see where countryTable is instantiated so I assume it's connected in InterfaceBuilder? And if this is the case, countryTable is only valid after viewDidLoad. But you could set delegate and dataSource in InterfaceBuilder as well.

By the way, every once you change the datasource (myArray), call countryTable.reloadData.