how to write TableViewController in objective-c

Asked on 08/02/2024

1 search

To write a UITableViewController in Objective-C, you can follow these steps:

  1. Create a new class that inherits from UITableViewController.

  2. Implement the required data source methods to populate the table view.

  3. Optionally, implement delegate methods to handle user interactions.

Here is a basic example:

#import <UIKit/UIKit.h>

@interface MyTableViewController : UITableViewController

@property (nonatomic, strong) NSArray *dataArray;

@end

@implementation MyTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Initialize your data array
    self.dataArray = @[@"Item 1", @"Item 2", @"Item 3"];
    
    // Register a cell class for reuse
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    // Configure the cell
    cell.textLabel.text = self.dataArray[indexPath.row];
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Handle row selection
    NSLog(@"Selected row: %@", self.dataArray[indexPath.row]);
}

@end

Explanation:

  1. viewDidLoad: This method is called after the view controller has loaded its view hierarchy into memory. Here, you initialize your data array and register a cell class for reuse.

  2. numberOfSectionsInTableView:: This method returns the number of sections in the table view. In this example, there is only one section.

  3. tableView:numberOfRowsInSection:: This method returns the number of rows in a given section. It uses the count of the dataArray.

  4. tableView:cellForRowAtIndexPath:: This method configures and returns a cell for a given index path. It dequeues a reusable cell and sets its text label to the corresponding item in the dataArray.

  5. tableView:didSelectRowAtIndexPath:: This delegate method is called when a row is selected. Here, it simply logs the selected item.

For more advanced features and customization, you can refer to the What's new in UIKit session from WWDC 2024, which covers updates and new APIs in UIKit, including improvements to table views.