在NSMutableArray的特定索引上添加一个对象

时间:2022-09-25 18:30:35

How can an object be added at a specific index of an NSMutableArray?

如何在NSMutableArray的特定索引上添加对象?

How is an object added to the front of the array?

如何将一个对象添加到数组的前面?

3 个解决方案

#1


215  

[myMutableArray insertObject:myObject atIndex:42];

To add an object to the front of the array, use 0 as the index:

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

[myMutableArray insertObject:myObject atIndex:0];

#2


42  

Take a look at the insertObject:atIndex: method of the NSMutableArray class. Adding to the "front" of the array implies index 0.

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

For example:

例如:

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


1  

Updated for Swift 3:

更新迅速3:

If you want to Add an object at a specific index of a NSMutableArray, use below a simple line of code:

如果您想在NSMutableArray的特定索引上添加一个对象,请使用下面的简单代码行:

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

Example: if you want to add string: "Nature" at index: 3

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

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

// Enjoy..! 

/ /享受. . !

#1


215  

[myMutableArray insertObject:myObject atIndex:42];

To add an object to the front of the array, use 0 as the index:

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

[myMutableArray insertObject:myObject atIndex:0];

#2


42  

Take a look at the insertObject:atIndex: method of the NSMutableArray class. Adding to the "front" of the array implies index 0.

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

For example:

例如:

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


1  

Updated for Swift 3:

更新迅速3:

If you want to Add an object at a specific index of a NSMutableArray, use below a simple line of code:

如果您想在NSMutableArray的特定索引上添加一个对象,请使用下面的简单代码行:

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

Example: if you want to add string: "Nature" at index: 3

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

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

// Enjoy..! 

/ /享受. . !