Gchammas23
Gchammas23

Reputation: 142

How to correctly set the number of rows of a tableview Xcode?

I was trying to set the number of rows for my table view in my controller using the following method:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.offers.count;
}

offers is an NSArray that I have declared and filled in the viewDidLoad method:

- (void)viewDidLoad {
    [super viewDidLoad];
    //Fill arrays accordingly
    if ([self.item  isEqualToString:@"Laptops"]){
        self.offers = @[@"MacBook Air", @"MacBook Pro", @"HP"];
        self.prices = @[@800, @1200, @600];
        self.offerNames = [[NSMutableArray alloc] init];
        self.offerPrices = [[NSMutableArray alloc] init];
        
        self.offerNames = [NSMutableArray arrayWithArray:_offers];
        self.offerPrices = [NSMutableArray arrayWithArray:_prices];
        
        
    }
}

When I try to run the app, I get the following error:

-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0xe4a88af02df0791a

I don't know exactly what's wrong in my code, and I never had this error before. P.S: I used the same method to set up the other table views in the other controllers and none gave this error.

That's the header file:

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface OffersTableViewController : UITableViewController

@property NSString *item;

@property (strong, nonatomic) NSMutableArray *offerNames;
@property (strong, nonatomic) NSMutableArray *offerPrices;

@end

NS_ASSUME_NONNULL_END

That's where I set the value of the item:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
    OffersTableViewController *offers = segue.destinationViewController;
    
    NSString *chosenItem = [[NSString alloc]init];
    
    if (isFiltered){
         chosenItem = filteredArray[indexPath.row];
    }
    else{
         chosenItem = self.itemNames[indexPath.row];
    }
    
    offers.item = chosenItem;
}

Thanks for the help 😊

Upvotes: 0

Views: 98

Answers (2)

Gchammas23
Gchammas23

Reputation: 142

After doing some debugging and after commenting out some lines of code and narrowing down my search. I realized that I needed to fix this line of code

cell.detailText.text = self.prices[indexPath.row];

To :

NSString *detailText = [NSString stringWithFormat: @"$ %@", self.prices[indexPath.row];
cell.detailText.text = detailText;

Upvotes: 0

Haspinder Singh
Haspinder Singh

Reputation: 109

Replace

if ([self.item  isEqualToString:@"Laptops"])

with

if ([[NSString stringWithFormat:@"%@", item] isEqualToString:@"Laptops"]])

Upvotes: 1

Related Questions