gpt4 book ai didi

ios - 将一个对象插入 NSMutable 数组并将元素向前移动一个位置 iOS

转载 作者:行者123 更新时间:2023-12-01 18:17:35 25 4
gpt4 key购买 nike

我想在 1 和 2 之间插入一个对象(比如 1.5)到 NSMutableArray(比如内容为 1,2,3,4 的数组)中。结果数组将是一个更大的元素(比如 1,1.5,2,3,4 )。

如何在 iOS 中使用 NSMutableArray 实现这一点?

最佳答案

假设您知道要插入的索引,只需使用 NSMutableArrayinsertObject:atIndex: (reference)。在你的情况下,你想要:

[yourMutableArray insertObject:@(1.5) atIndex:1];

如果您不知道索引,可以执行 this (copy-pasted because nobody likes broken links) 之类的操作:
@implementation NSMutableArray (SelfSorting)

- (void)insertNumberAtSortedLocation:(NSNumber *)aNumber
{
NSUInteger count = [self count];

// if there are no contents yet, simply add it
if (!count)
{
[self addObject:aNumber];
return;
}

NSRange searchRange;
searchRange.location = 0;
searchRange.length = count;


// bubble sort finding of insert point
do
{
NSInteger index = searchRange.location + searchRange.length/2;

NSNumber *testNumber = [self objectAtIndex:index];

switch ([aNumber compare:testNumber])
{
case NSOrderedAscending:
{
//searchRange.length = searchRange.length / 2;
searchRange.length = index - searchRange.location;
break;
}
case NSOrderedDescending:
{
int oldLocation = searchRange.location;
searchRange.location = index+1;
searchRange.length = searchRange.length - (searchRange.location - oldLocation);
break;
}
case NSOrderedSame:
{
searchRange.length = 0;
searchRange.location = index;
break;
}
}
} while (searchRange.length>0);

// insert at found point
[self insertObject:aNumber atIndex:searchRange.location];
}

然后,调用:
[yourMutableArray insertNumberAtSortedLocation:@(1.5)];

关于ios - 将一个对象插入 NSMutable 数组并将元素向前移动一个位置 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20287577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com