0

I have a textfield that I am trying to have the data sent to a Mutable Array when the user presses done. The only way this works is when I do textFieldArray = [[NSMutableArray alloc]initWithObjects:self.textField.text, nil]; but then it rewrites the mutable array when the user taps adds another object. Here is my code:

- (IBAction)doneButton:(id)sender {

[self resignFirstResponder];

[textFieldArray addObject:self.textField.text];

NSLog(@"array: %@", textFieldArray);
}

This may be flagged as a duplicate question but I cannot find anything that solves my problem, Thanks for helping.

6
  • What's wrong with the code you posted? The code appears to be correct. Commented Feb 18, 2014 at 17:21
  • @rmaddy it doesn't add the object to the array. When I log it it says (null) Commented Feb 18, 2014 at 17:22
  • Then you never initialize the array. Commented Feb 18, 2014 at 17:23
  • @rmaddy Thanks, just tried that but it just overwrites whatever is in the array, not add to the array. Commented Feb 18, 2014 at 17:26
  • Where are you initializing the array? It should be done once in the proper init method. Commented Feb 18, 2014 at 17:27

2 Answers 2

1

Just add this to viewDidLoad: method and it should work fine:

textFieldArray = [[NSMutableArray alloc]init];

You need to allocate and initialise this array,but not every time you adding new object in Array.

Sign up to request clarification or add additional context in comments.

4 Comments

I'd put this in the proper init... method since it really has nothing to do with views.
@Greg My bad it does work, I had a typo in my code. Thanks for the help.
Have you added this line I posted to viewDidLoad and it still override the data?
@Greg I put it in the viewDidLoad: method, i had a typo in my code but it works fine now, really appreciate the help!
1

Try this:

- (IBAction)doneButton:(id)sender {
     if(!textFieldArray)
     {
         textFieldArray = [[NSMutableArray alloc]initWithObjects:self.textField.text, nil];
     }
     else
     {
        [textFieldArray addObject:self.textField.text];
     }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.