Luckabo Luckabo - 10 months ago 84
Objective-C Question

Using Text Field to add String to NSMutableArray

I am looking to get an NSString value from a Text Field and add it to an array, I want to build an array with many strings in it ex:
[hello, goodbye, too soon].

This is my current solution:

- (IBAction)submitButton:(id)sender {

NSMutableArray *wordArray = [[NSMutableArray alloc] init];
NSString *input = textField.text;
[wordArray insertObject:input atIndex:arrayIndex];

This works for the first item in the array, but when I press submit again it reinitializes.My issue is how do I initialize the NSMutableArray to use in the button function, without having it in there so that it doesn't initialize every time. Thank you

Answer Source

Honey's answer is almost, but not, correct.

Your code uses a local variable in your submitButton method, and creates a new, empty array each time the method gets called. Both of those things are wrong.

Honey's answer has you create a different local variable in viewDidLoad. That's also wrong.

You need to make wordArray an instance variable or property of your class. If you class is called ViewController, say, it might look like this

@interface ViewController: UIViewController;

@property (nonatomic, strong) NSMutableArray *wordArray



And then initialize it in viewDidLoad:

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    self.wordArray = [[NSMutableArray alloc] init];

Then in the rest of your program refer to self.wordArray, the property.