Objective c 如何将字符串对象添加到NSMutableArray

Objective c 如何将字符串对象添加到NSMutableArray,objective-c,nsmutablearray,Objective C,Nsmutablearray,我有一个名为randomSelection的NSMutableArray: NSMutableArray *randomSelection; 如果满足某些条件,我将尝试向该数组添加字符串: [randomSelection addObject:@"string1"]; 然后,我尝试输出字符串,以确定它是否已添加该字符串: NSString *test = [randomSelection objectAtIndex:0]; NSLog(test); 然而,没有任何东西被输出到错误日志中,我

我有一个名为randomSelection的NSMutableArray:

NSMutableArray *randomSelection;
如果满足某些条件,我将尝试向该数组添加字符串:

[randomSelection addObject:@"string1"];
然后,我尝试输出字符串,以确定它是否已添加该字符串:

NSString *test = [randomSelection objectAtIndex:0];
NSLog(test);
然而,没有任何东西被输出到错误日志中,我不知道为什么


非常感谢您的帮助/提示。

我认为您缺少为阵列分配内存的功能。所以试试这个

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

您需要先分配它。

首先使用以下语句分配数组,然后分配其中的对象

NSMutableArray *randomSelection =  [[NSMutableArray alloc] init];
[randomSelection addObject:[NSString stringWithFormat:@"String1"]];
[randomSelection addObject:[NSString stringWithFormat:@"String2"]];
NSLog(@"Array - %@", randomSelection);
这肯定会解决您的问题。

尝试以下方法:

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

只需分配NSMutableArray即可。你的问题会得到解决。

斯威夫特:

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


是否确定满足添加字符串的特定条件?否则,您可能应该尝试NSLog(@“%@”,test);是的,符合标准。就在我放置的NSLog(test)下面:NSLog(“makeit!”);正在显示。我需要初始化NSMutable数组并使用足够的空间或其他什么吗?我认为这就是这个addObject函数的意义所在,这样我就不必这么做了。@David Brunow请在发表任何评论或回答之前阅读问题。。。。这家伙没有分配“NSMutableArray*randomSelection;”,所以他希望如何获得数组对象…@SamBo确实忘记了分配内存并初始化它。现在数组被声明了,但没有定义。@奥菲修斯也有同样的问题。至少现在我知道我需要首先为数组分配内存。但是,有没有一种更通用的方法来指定您只想在数组中添加字符串?对我来说很有用..谢谢你,伙计...)
var randomSelection: [AnyObject] = [AnyObject]()
randomSelection.append("string1")
let test: String = randomSelection[0] as! String
print(test)
let array : NSMutableArray = []
array.addObject("test String")
print(array)