Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 833
Cocoa Dev Avatar asked Feb 08 '11 21:02

Cocoa Dev


2 Answers

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.

like image 52
WrightsCS Avatar answered Nov 14 '22 19:11

WrightsCS


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.

like image 1
easyDeal Avatar answered Nov 14 '22 20:11

easyDeal