Iphone – How to add an object to NSMutableArray in Objective C

iphonensmutablearray

NSMutableArray *tblContents =  [NSMutableArray arrayWithObjects: @"1", @"2", @"3", nil];
[tblContents addObject:txtNewTableRow.text];

My app is crashing at line 2.
Error message in console is
'NSInvalidArgumentException', reason: '-[NSCFString addObject:]: unrecognized selector sent to instance xxx

BTW, it works alright if i replace arraywithobjects initialization with alloc & init!

I am simply creating a mutable array and adding an object to it. Whats the problem in there?

Thanks
Sridhar Reddy

Full code:
.h:

#import <UIKit/UIKit.h>

@interface TableStarterViewController : UIViewController
<UITableViewDelegate, UITableViewDataSource>
{
    NSMutableArray *tblContents;

    IBOutlet UITextField *txtNewTableRow;
    IBOutlet UITableView *tblMain;
}

@property (nonatomic, retain) NSMutableArray *tblContents;
@property (nonatomic, retain) UITextField *txtNewTableRow;
@property (nonatomic, retain) UITableView *tblMain;

-(IBAction) addRowToTable;

@end

.m:

#import "TableStarterViewController.h"

@implementation TableStarterViewController

@synthesize tblContents;
@synthesize txtNewTableRow;
@synthesize tblMain;

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

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] 
                             initWithStyle:UITableViewCellStyleDefault 
                             reuseIdentifier:@"cell"];

    cell.textLabel.text = [tblContents objectAtIndex:indexPath.row];

    return cell;
}

-(IBAction) addRowToTable
{
    [tblContents addObject:txtNewTableRow.text];

    [tblMain reloadData];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    tblContents =  [NSMutableArray arrayWithObjects: @"1", @"2", @"3", nil];


    [super viewDidLoad];
}

Thats all code.

Best Answer

Your are not retaining the array and it is being autoreleased before you are using it. Make sure to retain it after you get the pointer back from arrayWithObjects.

Also, it's not clear to me that arrayWithObjects will return a mutable array. Which, if not, will cause further problems.

Edit 1: Alloc and Init return an object with retain count 1; arrayWithObjects returns an object with retain count 0.

Edit 2: I pulled out Xcode and verified that [NSMutableArray arrayWithObjects:] return an NSMutableArray (or according to Xcode a __NSArrayM)

Related Topic