如何在NSArray中交换值的索引

8

我有一个NSArray,里面装有一些值。

NSArray *testArray = [NSArray arrayWithObjects:@"Test 1", @"Test 2", @"Test 3", @"Test 4", @"Test 5", nil];
NSLog(@"%@", testArray);

结果如下:

(
"Test 1",
"Test 2",
"Test 3",
"Test 4",
"Test 5"
)

现在我希望的结果是这样的:
(
"Test 3",
"Test 5",
"Test 1",
"Test 2",
"Test 4"
)

有没有办法在不重新初始化数组的情况下完成这个操作?我能否交换此数组的值?

2
NSArray是静态的,因此您甚至无法向其中添加任何内容,更不用说对条目进行洗牌了。但是NSMutableArray有一个名为sortUsingSelector的函数。使用此方法,您可以确定自己的排序顺序。 - ATaylor
@ATaylor:在NSMutableArray中是否可能? - Bhavin_m
@B.M.W. 可以在 NSMutableArray 中实现。 - Aman Aggarwal
可能是如何对NSMutableArray进行最佳洗牌?的重复问题。 - Monolo
2个回答

8

使用 NSMutableArray 来交换两个对象。

- exchangeObjectAtIndex:withObjectAtIndex:

这会交换数组中给定索引(idx1和idx2)的对象。

idx1
要替换idx2处对象的对象的索引。

idx2
要替换idx1处对象的对象的索引。

SWIFT

func exchangeObjectAtIndex(_ idx1: Int,
         withObjectAtIndex idx2: Int)

OBJECTIVE-C 使用NSMutableArray

  - (void)exchangeObjectAtIndex:(NSUInteger)idx1
                withObjectAtIndex:(NSUInteger)idx2

如何在NSMutableArray中交换元素


7

你的数组必须是NSMutableArray的实例,否则不允许写入方法(NSArray只读)

请使用以下方法:

- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject

您将需要一个临时存储空间来存储替换对象:

id tempObj = [testArray objectAtIndex:index];
[testArray replaceObjectAtIndex:index withObject:[testArray objectAtIndex:otherIndex]];
[testArray replaceObjectAtIndex:otherIndex withObject:tempObj];

20
你可以使用exchangeObjectAtIndex:withObjectAtIndex:,这样就不需要临时对象了。 - Martin R
2
嗨@MartinR,你考虑过把你的评论转成回答帖吗?这真的是一个可接受的做法。感谢你指出那个API! - Daniel Galasko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接