1

I have a very simple task: add the contents of a textField to an NSMutableArray.The Problem is the array is returning nill. I believe that it has something to do with the fact that the array I'm using is declared as an instance variable.

/*
 IBOutlet NSTextField *textField;
 IBOutlet NSTabView *tableView;
 IBOutlet NSButton *button;
 NSMutableArray *myArray;
 */

#import "AppController.h"


@implementation AppController


-(IBAction)addNewItem:(id)sender
{
    NSString *string = [textField stringValue];
    NSLog(@"%@",string);

    [myArray addObject:string];
    NSLog(@"%d",[myArray count]);//this outputs 0 why is that?

}
2

1 Answer 1

6

Did you do the following somewhere?

myArray = [[NSMutableArray alloc] init];

If you don't do something like that, myArray is just a null pointer and the addObject call will just silently do nothing.


Edit: The idea here is that no NSMutableArray object has been created if you just have a pointer variable. Until the alloc and init are called, there's no object.

Check out this CocoaDev page for more information on NSMutableArray and its use. And the Apple documentation has information on the NSMutableArray methods.


Also, this is essentially the same question as this SO question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.