Search code examples
iosobjective-cuitableviewunrecognized-selector

Errors Changing Data in a TableView Objective C


I've been working on an example of a tableview out of the Nutting, Olsson, and Mark iOS7 textbook. I have a tableview working well, so I added a button to my view. When I touch up inside the button, it calls the method addData. addData merely appends another object to the array that is being displayed in the table.

The code compiles great, but when I click the button, it crashes. Why is this? I don't understand the error message, but here's the code.

#import "ViewController.h"
@interface ViewController ()
@property (copy, nonatomic) NSMutableArray* dwarves;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.dwarves = @[@1.5,@2.,@2.5,@3.,@3.5,@4.,@4.5,@5.,@5.5,@6.,@6.5,@7.];
UITableView *tableView = (id)[self.view viewWithTag:1];
UIEdgeInsets contentInset = tableView.contentInset;
contentInset.top = 20;
[tableView setContentInset:contentInset];
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                         SimpleTableIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc]
            initWithStyle:UITableViewCellStyleDefault
            reuseIdentifier:SimpleTableIdentifier];
}
cell.textLabel.text = [NSString stringWithFormat:@"%@",self.dwarves[indexPath.row]];
return cell;
}

- (IBAction)addData:(id)sender {
[_dwarves addObject:@100];
}
@end

Here's the error:

2015-05-28 18:37:24.449 TableView Practice[3630:145774] -[__NSArrayI addObject:]: unrecognized selector sent to instance 0x7924aa40
2015-05-28 18:37:24.453 TableView Practice[3630:145774] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x7924aa40'

What's wrong with this code?


Solution

  • No matter how you declared dwarves, it is an NSArray and not an NSMutableArray. Therefore addObject crashes. I believe the combination of "copy" property and mutable type doesn't do what you think it should do.

    Better make "dwarves" just a normal "strong" property, but initialise

    self.dwarves = [@[@1.5,@2.,@2.5,@3.,@3.5,@4.,@4.5,@5.,@5.5,@6.,@6.5,@7.] mutableCopy];