robk
robk

Reputation: 3

uitableview array of objects as datasource

i have a UITableView in a storyboard in an ios xcode project,

i also have an array of menuitem objects stored in itemarray:

NSMutableArray *itemarray;

this is my menuitem.h file

#import <Foundation/Foundation.h>
@interface menuitem : NSObject
@property (nonatomic) NSString *itemtitle;
@property (nonatomic) NSString  *itemdesc;
@property (nonatomic) int itemid;
@property (nonatomic) int itemprice;
@property (nonatomic) NSString  *itemcat;
@end

this is my tableviewcell.m file:

#import "tableviewcell.h"
#import "menuitem.h"
@interface tableviewcell ()
@property (nonatomic, weak) IBOutlet UILabel *titleLabel;
@property (nonatomic, weak) IBOutlet UILabel *descLabel;
@property (nonatomic, weak) IBOutlet UILabel *priceLabel;


@end

@implementation tableviewcell
-(void)configureWithmenuitem:(menuitem *)item{
    NSLog(@"hello");

    self.titleLabel.text = item.itemtitle;
    self.descLabel.text = item.itemdesc;

    self.priceLabel.text = [NSString stringWithFormat:@"%.1d", item.itemprice];
}

@end

i want to get the itemtitle, itemdesc and itemprice from each instance of menuitem into 3 labels on each of the tableviewcells

Upvotes: 0

Views: 952

Answers (1)

Lord Zsolt
Lord Zsolt

Reputation: 6557

Your tableviewcell is a View and thus it should only know how to display itself and not what to display. It's the job of your controller (through the delegate tableView:cellForRowAtIndexPath: method) to tell the view what to display.

Thus you should do something like:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
      CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Id"];

      //Assuming you've stored your items in an array.
      Item *item = [items objectAtIndex:indexPath.row];

      cell.titleLabel.text = item.itemTitle;
      cell.descLabel.text = item.itemdesc;
      cell.priceLabel.text = [NSString stringWithFormat:@"%.1d", item.itemprice];
      return cell;
}

^ The above code assumes you have a prototype cell. If you don't, you'll have to alloc if cell is nil after dequeue.

Upvotes: 1

Related Questions