Search code examples
iosobjective-cuitableviewnsarraynsdictionary

How to display NSArray objects using dictionary in UITableViewCell


Here is my viewcontroller.m

@interface ViewController ()

{

    NSArray *sectionTitleArray;
}

   @property (strong, nonatomic) IBOutlet UITableView * tablevw;

- (void)viewDidLoad
{
    [super viewDidLoad];

    _tablevw.delegate = self;
    _tablevw.dataSource = self;



    sectionTitleArray = @[ @{@"text": @"About Step0ne"},
                           @{@"text": @"Profile"},
                           @{@"text": @"Matches"},
                           @{@"text": @"Messages"},
                           @{@"text": @"Photos"},
                           @{@"text": @"Settings"},
                           @{@"text": @"Privacy"},
                           @{@"text": @"Reporting issues"},
                           ];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {

    return sectionTitleArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }

    cell.textLabel.text = [[sectionTitleArray objectAtIndex:indexPath.row]objectForKey:@"text"];

        return cell;
}

I am new to Xcode am getting output as in every tableview cell first object i.e About Step0ne is displaying i need all objects should be displayed in UITableView cell.Any help is appreciable.


Solution

  • Since you have "count" sections, each with one row, you need to change this line:

    cell.textLabel.text = [[sectionTitleArray objectAtIndex:indexPath.row]objectForKey:@"text"];
    

    to:

    cell.textLabel.text = [[sectionTitleArray objectAtIndex:indexPath.section]objectForKey:@"text"];
    

    BTW - this can be written more easily as:

    cell.textLabel.text = sectionTitleArray[indexPath.section][@"text"];
    

    Or, if you really want one section with "count" rows, leave that line as-is and update your numberOfRowsInSection and numberOfSectionsInTableView accordingly.