How to add string objects to NSMutableArray

SamBo picture SamBo · Dec 12, 2012 · Viewed 81.7k times · Source

I have an NSMutableArray named randomSelection:

NSMutableArray *randomSelection;

I am then trying to add strings to this array if certain criteria are met:

[randomSelection addObject:@"string1"];

I am then trying to output the string, to determine if it has added it:

NSString *test = [randomSelection objectAtIndex:0];
NSLog(test);

However nothing is being output to the error log and I can't figure out why.

Any help/hints appreciated.

Answer

hp iOS Coder picture hp iOS Coder · Dec 12, 2012

I think you are missing to allocate the memory for array. So try this

NSMutableArray *randomSelection = [[NSMutableArray alloc] init];
[randomSelection addObject:@"string1"];
NSString *test = [randomSelection objectAtIndex:0];
NSLog(test);