UITableView and ViewDidLoad method

11,880

Solution 1

Updated Answer:

You should not be doing this in viewdidLoad in the first place. Its a bad practice, you should do it in cellForRowAtIndexPath:.

More explaination:

The table is not loaded as of yet in viewDidLoad. You have to do [self.tableView reloadData]; before doing anything else. Doing that will call the delegate methods for table (it has no idea how many cells there are so getting the cell for any specfic index path doesn't make sense). See Table View Programming guide.

Also:

UITableViewCell *cell = [[UITableViewCell alloc] init];
cell = [self.tableView cellForRowAtIndexPath:lastIndexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;

First, this is wrong. You are leaking memory with that alloc/init. Just do:

UITableViewCell *cell = nil;
cell = [self.tableView cellForRowAtIndexPath:lastIndexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;

Solution 2

You need a call to UITableView's - scrollToRowAtIndexPath:atScrollPosition:animated: method. I would put this the viewDidAppear: method of your UITableViewController. See UITableView Class Reference.

Share:
11,880
Alick Dikan
Author by

Alick Dikan

Updated on June 04, 2022

Comments

  • Alick Dikan
    Alick Dikan almost 2 years

    In my app I have a UITableViewCobtroller which creates the table view with checkmark accessory type. Table View loads and works correctly. In didSelectRowAtIndex method I wrote method of adding data in sqlite dataBase:

            [self.dataBaseController openSettingsDB];
            [self.dataBaseController updateRecordIntoTableNamed:kTableName withField:kSField1Name fieldValue:newCell.textLabel.text];
            [self.dataBaseController closeDB];
    

    It works well. So what I want is to retrieve the recorded data from dataBase and when the application is relaunched to select the row, that has the title, that I retrieved from sqlite dataBase.

    I tried this:

    -(void)viewDidLoad
    {
        NSArray *array = [[NSArray alloc] initWithObjects:
                          kCourse1, kCourse2, kCourse3, kCourse4, kCourse5, kCourse6, nil];
        self.list = array;
        [self.dataBaseController openSettingsDB];
        [self.dataBaseController getRowFromTableNamed:kTableName whichRow:kSField1Name];
        self.chosenStr = self.dataBaseController.dataString;
        [lastIndexPath indexAtPosition:[array indexOfObjectIdenticalTo:self.chosenStr]];
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        cell = [self.tableView cellForRowAtIndexPath:lastIndexPath];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [self.tableView reloadData];
        [array release];
        [super viewDidLoad];
    }
    

    But it doesn't work. Please, suggest me any ideas. Thanks in advance.

    Alick