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

标签 ios objective-c arrays nsmutablearray

我想在 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/

相关文章:

php - 如何在 PHP 中动态绑定(bind) mysqli bind_param 参数?

iphone - 从 block 中返回整数

javascript - 使用 TypeScript react Children[] 问题

ios - 以编程方式导航到另一个 View Controller /场景

objective-c - 弧: how do I dealloc at the end of object life cycle?

ios - UIActivityViewController 在 iOS 11 中不起作用

ios - 动画贝塞尔曲线就像在 iPhone 屏幕上进行绘图一样

php - 制作一个多维数组php mysql

ios - tableView 转换点 : fromView: odd behaviour and workaround

ios - AFNetworking 没有构建正确的 URL?