user3739958
user3739958

Reputation: 37

NSMutable array won't add atIndex:0?

I have searched online and am at a loss.

I have a text field and when a user types something in and presses 'return' the text will save to my NSMutablearray (userAnswers)

NSMutableArray *userAnswers;

in my init method I have allocated the array:

userAnswers = [[NSMutableArray alloc] initWithObjects:@"Test", nil];

have also tried:

userAnswers = [[NSMutableArray alloc] init];

//When the user presses 'return' on keypad

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[answerText resignFirstResponder];

if (levelSelected == 1) {
    [userAnswers insertObject:answerText.text atIndex:0];
    [userAnswers replaceObjectAtIndex:0 withObject:answerText.text];
    //Have tried both of these!
    NSLog(@"SHOULD INSERT INTO ARRAY");//This prints because level one is selected
  }
    NSLog(@"ARRAY: %@", userAnswers); //Just print null
}

I have no idea what I am doing wrong??

Thanks for any help!

Upvotes: 0

Views: 69

Answers (3)

Akhil Shrivastav
Akhil Shrivastav

Reputation: 437

If you are using storyboard allocate array in initWithCoder instead init.

Initializing a View Controller

Upvotes: 0

BHASKAR
BHASKAR

Reputation: 1201

I think your array is not allocated when the function is call so you can try to alloc your array in viewDidLoad:. And also decleare your array in .h file not in init or viewDidLoad:

Upvotes: 0

Julian
Julian

Reputation: 9337

It looks like your array is not allocated at the moment of the insertion and it even prints this (as you commented). You should allocate the array before putting there anything. Your allocation has to be placed in the wrong place so at the returning stage the array is nil or you are assigning nil to the array reference at some point. The reason the array is nil may also depend on how you declared that ivar. This is what I can say on the basis of this code sample.

Upvotes: 1

Related Questions