I've been having this problem a lot where the table view either doesn't load the cells the first time or displays temporary labels. In both cases, when the table is loaded a second time (by another button in which I force it to reload or by going to the previous view in the app and going back to the table) everything shows up as it was supposed to.
Im using [table reloadData]
to reload the table in the viewDidAppear:
method as it didn't work in the viewDidAppear:
method and in another case I put it in a button action.
I'm also using this method to set the label of the cell that I have placed in the storyboard:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"Cell";
UITableViewCell *cell = [contactsTableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
UILabel *label = (UILabel *)[cell viewWithTag:1001];
label.text = [Array3 objectAtIndex:indexPath.row];
return cell;
}
EDIT
I declare the array below the implementation like: NSMutableArray * Array3; After that in the ViewDidLoad method I declare the rest of the array: Array3 = [NSMutableArray arrayWithObjects: nil]; Then I load the elements in the array by calling a function within the ViewDidLoad method to fill the array with elements.
EDIT 2 Showing more of how I populate the array - (void)viewDidLoad {
[super viewDidLoad];
Array3 = [NSMutableArray arrayWithObjects: nil];
[self loadArray];
}
- (void) loadArray
//populate array in here.
// I use the add object method
// [Array3 addobject:object];
{
Good news first: Your method cellForRowAtIndexPath
is correct.
There is no need to invoke reloadData
in neither -viewDidAppear:
nor -viewWillAppear
. This remark may not hold true if you modify the content of Array3 while your view is covered, which is a special case.
It is not a matter of where you define your method, but where you invoke it. A reasonable place to populate the content of Array3 is in
required init(coder aDecoder: NSCoder!)
or
override func viewDidLoad()
Pitfalls
Additionally, you need all your delegate methods (numberOfSectionsInTableView
, numberOfRowsInSection
, cellForRowAtIndexPath
) to be returning consistent values, in accordance to your array. A simple technique is to use the number of entries in the array to drive numberOfRowsInSection
.
When to use reloadData?
A typical use of reloadData
is shown below:
- (void)loadArray {
//populate array in here.
...
[self.tableview reloadData]; // Possibly postpone to main thread
}