在NSMutableArray的特定索引处添加对象


Answers:


225
[myMutableArray insertObject:myObject atIndex:42];

要将对象添加到数组的前面,请使用0作为索引:

[myMutableArray insertObject:myObject atIndex:0];

6
如果我尝试在当前没有数据的新分配的可变数组上运行第一条语句怎么办?
NaXir 2015年

很棒的答案!谢谢
Genevios

42

看一下NSMutableArray类的insertObject:atIndex:方法。添加到数组的“最前面”意味着索引为0。

例如:

NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity:3];
[array addObject:@"b"]; // Contains "b"
[array insertObject:@"a" atIndex:0]; // Contains "a", "b"
[array insertObject:@"c" atIndex:2]; // Contains "a", "b", "c"

3

为Swift 3更新:

如果要在NSMutableArray的特定索引处添加对象,请在下面的简单代码行中使用:

self.yourMutableArrayName.insert(<#T##newElement: String##String#>, at: <#T##Int#>)

示例:如果要在索引:3处添加字符串:“ Nature”

var str = "Nature"
self.yourMutableArrayName.insert(str, at: 3) 

// 请享用..!

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.