How to add string objects to NSMutableArray

倖福魔咒の 提交于 2019-12-18 13:54: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.


回答1:


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



回答2:


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

You need to alloc it first.




回答3:


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.




回答4:


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




回答5:


Try this:

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



回答6:


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)


来源:https://stackoverflow.com/questions/13834390/how-to-add-string-objects-to-nsmutablearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!