Reputation: 13860
I'm a little confused how to use IndexPath to add row into TableView. In first i init:
tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
//rows code here
[self.view addSubview:tableView];
Now between this two i would like to add some row to my table View. I have an NSArray with NSStrings contains elements name.
So i try this:
[[self tableView] beginUpdates];
[[self tableView] insertRowsAtIndexPaths:(NSArray *)myNames withRowAnimation:UITableViewRowAnimationNone];
[[self tableView] endUpdates];
Then I've read that I should first add this somehow to UITableViewDataSource. So i declared it wrong? I'm asking becouse i'd rather avoid unnecessary passing data.
Upvotes: 0
Views: 225
Reputation: 62676
The idea of the table view - and most views in MVC - is that they reflect the state of the model. So, yes, as you suggested, have your datasource maintain an array:
@property (strong, nonatomic) NSMutableArray *array;
Make changes to the array:
[self.array addObject:@"New Object"];
Record what rows have changed...
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.array count]-1 inSection:0];
NSArray *myNames = [NSArray arrayWithObject:indexPath];
Then let the table view know that the model is different using the code you posted...
[[self tableView] beginUpdates];
[[self tableView] insertRowsAtIndexPaths:myNames withRowAnimation:UITableViewRowAnimationNone];
[[self tableView] endUpdates];
Upvotes: 1
Reputation: 36
AFAIK that's not a very good way to add data to a UITableView. I misunderstood what you were trying to do, in either case you need to setup your tableview's datasource like this:
tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
[tableView setDataSource:self];
[self.view addSubview:tableView];
Then you need to implement the UITableViewDataSource protocol (and probably UITableViewDelegate). You will want to implement the following datasource methods:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [myNames count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [[[UITableViewCell alloc] initWithCellStyleDefault reuseIdentifier@"MyIdentifier"] autorelease];
[[cell textLabel] setText:[myNames objectAtIndex:[indexPath row]]];
return cell;
}
You might want to read up on the Reuse Identifier, it's necessary to ensure that your tables scroll smoothly and don't take up too much memory.
Upvotes: 1