2 Stimmen

Wie man ein Objekt zu NSMutableArray in Objective C hinzufügen?

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

Meine Anwendung stürzt in Zeile 2 ab. Die Fehlermeldung in der Konsole lautet NSInvalidArgumentException', Grund: '-[NSCFString addObject:]: unerkannter Selektor an Instanz xxx gesendet

BTW, es funktioniert in Ordnung, wenn ich Arraywithobjects Initialisierung mit alloc & init ersetzen!

Ich erstelle einfach ein veränderbares Array und füge ihm ein Objekt hinzu. Was ist das Problem dabei?

Danke Sridhar Reddy

Vollständiger 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];
}

Das ist alles Code.

2voto

Ankur Punkte 271

Anstelle von,

tblContents =  [NSMutableArray arrayWithObjects: @"1", @"2", @"3", nil];

Versuchen Sie dies,

tblContents =  [NSMutableArray initWithObjects: @"1", @"2", @"3", nil];

0voto

Null Head Punkte 2745

Wie von aepryus erwähnt, wird arrayWithObjects von NSArray geerbt und es könnte tatsächlich NSArray zurückgeben. Daher das Problem. Weiß jemand, wie NSMutableArray mit Objekten zu initiieren?

CodeJaeger.com

CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.

Powered by:

X