Day*_*ana 1 objective-c nsarray ios
NSarray 的简单问题。我将对象存储在 NSMuteableArray 中。[对象1、对象2、对象3]
如果选择了一个对象,我想把它放在数组的前面。即如果选择了 obj3,则:
[obj3, obj1, obj2]
下面的工作或复制 obj3 吗?另外,这可以使线程安全吗?
[myMutableArray insertObject:obj3 atIndex:0];
Run Code Online (Sandbox Code Playgroud)
假设您需要保留其他元素的顺序,则需要删除然后插入有问题的对象:
NSMutableArray *array = ... // array with objects
NSInteger index = ... // index of object to move to the front
id obj = array[index];
[array removeObjectAtIndex:index];
[array insertObject:obj atIndex:0];
Run Code Online (Sandbox Code Playgroud)
您的代码将obj3在数组的前面插入另一个引用(即数组现在将包含 4 个元素),但它实际上不会复制对象。
你需要使用exchangeObjectAtIndex:withObjectAtIndex-
[myMutableArray exchangeObjectAtIndex:0 withObjectAtIndex:selectedIndex]
Run Code Online (Sandbox Code Playgroud)
其中selectedIndex是所选对象的索引。
NSMutableArray不是线程安全的,因此@synchronizsed(myMutableArray)如果您可能从多个线程修改它或在另一个线程迭代它时修改它,则需要环绕对该数组的访问。
如果要保留第一个元素以外的数组顺序,则需要执行单独的删除和插入操作 -
id someObject=myMutableArray[selectedIndex];
[myMutableArray removeObjectAtIndex:selectedIndex];
[myMutableArray insertObject:someObject atIndex:0];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1480 次 |
| 最近记录: |