SamBo
SamBo

Reputation: 551

How to add string objects to NSMutableArray

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.

Upvotes: 31

Views: 85253

Answers (6)

Alvin George
Alvin George

Reputation: 14296

Swift :

var randomSelection: [AnyObject] = [AnyObject]()
randomSelection.append("string1")
let test: String = randomSelection[0] as! String
print(test)

OR

let array : NSMutableArray = []
array.addObject("test String")
print(array)

Upvotes: 0

Pratik Mistry
Pratik Mistry

Reputation: 2935

NSMutableArray *randomSelection =  [[NSMutableArray alloc]init];
[randomSelection addObject:@"string1"];

You need to alloc it first.

Upvotes: 5

Rahul Gupta
Rahul Gupta

Reputation: 808

Try this:

NSMutableArray *randomSelection = [[NSMutableArray alloc]init]; 
[randomSelection addObject:@"string1"];

Upvotes: 1

Sunil Targe
Sunil Targe

Reputation: 7459

Just allocate your NSMutableArray. You'll get solved your problem.

Upvotes: 1

Girish
Girish

Reputation: 4712

First allocate the array using following statement & then objects in it.

NSMutableArray *randomSelection =  [[NSMutableArray alloc] init];
[randomSelection addObject:[NSString stringWithFormat:@"String1"]];
[randomSelection addObject:[NSString stringWithFormat:@"String2"]];
NSLog(@"Array - %@", randomSelection);

This will definitely solves your problem.

Upvotes: 2

hp iOS Coder
hp iOS Coder

Reputation: 3234

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

Upvotes: 68

Related Questions