Luckabo
Luckabo

Reputation: 74

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];
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

Upvotes: 0

Views: 216

Answers (3)

Ali Omari
Ali Omari

Reputation: 371

Here's the solution,

@implementation ViewController{
   NSMutableArray *_wordArray;
}
- (void)viewDidLoad { 
    [super viewDidLoad]; 
    _wordArray = [[NSMutableArray alloc] init];
}

- (IBAction)submitButton:(id)sender {
    NSString *input = textField.text;
    [wordArray addObject:input];
}

You was re init the array each time you make the action, which will let you always save the last value of the textfield. but this creates an array as global variable so that you can add all the values entered in textfield.

Hope this help you :)

Upvotes: 0

Duncan C
Duncan C

Reputation: 131418

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

...

@end

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.

Upvotes: 0

rmaddy
rmaddy

Reputation: 318804

Your are using a local array that disappears as soon as the submitButton method is finished.

Make your wordArray an instance variable and initialize it once in viewDidLoad. Then in your submitButton: method (and any others), you reference the instance variable instead of creating local arrays.

Upvotes: 2

Related Questions