How to add string objects to NSMutableArray

2019-02-07 18:20发布

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.

6条回答
姐就是有狂的资本
2楼-- · 2019-02-07 18:43

Try this:

NSMutableArray *randomSelection = [[NSMutableArray alloc]init]; 
[randomSelection addObject:@"string1"];
查看更多
对你真心纯属浪费
3楼-- · 2019-02-07 18:48

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)
查看更多
冷血范
4楼-- · 2019-02-07 18:50

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);
查看更多
闹够了就滚
5楼-- · 2019-02-07 18:51
NSMutableArray *randomSelection =  [[NSMutableArray alloc]init];
[randomSelection addObject:@"string1"];

You need to alloc it first.

查看更多
老娘就宠你
6楼-- · 2019-02-07 18:58

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.

查看更多
Evening l夕情丶
7楼-- · 2019-02-07 19:01

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

查看更多
登录 后发表回答