29

我有一个名为 randomSelection 的 NSMutableArray:

NSMutableArray *randomSelection;

然后,如果满足某些条件,我将尝试将字符串添加到该数组中:

[randomSelection addObject:@"string1"];

然后我试图输出字符串,以确定它是否添加了它:

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

但是没有任何东西输出到错误日志中,我不知道为什么。

任何帮助/提示表示赞赏。

4

6 回答 6

66

我认为您缺少为数组分配内存。所以试试这个

NSMutableArray *randomSelection = [[NSMutableArray alloc] init];
[randomSelection addObject:@"string1"];
NSString *test = [randomSelection objectAtIndex:0];
NSLog(test);
于 2012-12-12T07:00:58.493 回答
5
NSMutableArray *randomSelection =  [[NSMutableArray alloc]init];
[randomSelection addObject:@"string1"];

你需要先分配它。

于 2012-12-12T07:01:38.210 回答
4

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

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

这肯定会解决你的问题。

于 2012-12-12T07:14:51.473 回答
3

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

于 2012-12-12T07:29:36.653 回答
2

尝试这个:

NSMutableArray *randomSelection = [[NSMutableArray alloc]init]; 
[randomSelection addObject:@"string1"];
于 2012-12-12T07:20:10.057 回答
0

斯威夫特:

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)
于 2016-02-11T07:58:19.863 回答