I have a UITableView in my app where I have the user add rows to the table. I do this by calling "insertRowAtIndexPath":
- (IBAction)addRow:(id)sender {
NSString *theObjectToInsert = [NSString stringWithFormat:@"Row #: %lu", (unsigned long)[self.tableData count]];
[self.tableData addObject:theObjectToInsert];
NSLog(@"What is the count of the collection? %lu", self.tableData.count-1);
NSIndexPath *newPath=[NSIndexPath indexPathForRow:self.tableData.count-1 inSection:0];
[self.myTable insertRowsAtIndexPaths:@[newPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.myTable scrollToRowAtIndexPath:newPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
My problem that I've discovered is that after adding the necessary rows, I am not saving the data as I think I should. Here is the method that is supposed to store the data:
- (void)saveAction {
//I iterate through my entire UITableView to tally up the data from all of the rows
NSMutableArray *cells = [[NSMutableArray alloc] init];
for (NSInteger j = 0; j < [self.myTable numberOfSections]; ++j) {
for (NSInteger i = 0; i < [self.myTable numberOfRowsInSection:j]; ++i) {
if ([self.myTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:j]]) {
[cells addObject:[self.myTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:j]]];
}
}
}
NSLog(@"The number of table rows are: %lu", (unsigned long)[cells count]);
}
For some reason, this only prints out "4", even though I've added much more. What am I doing wrong?
Why would u save the UITableViewCell
in the cells array? while u already have all the datas in the self.tableData
array. Never store/access the UI object, just use the datamodel.
And coming to the point, from UITableView
docs, the cellForRowAtIndexPath
returns nil if the cell is not visible. So even though you have 10 cells, if only 4 cells are visible, then this method will return nil for the remaining 6 cells.
- (nullable __kindof UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath;
// returns nil if cell is not visible or index path is out of range