将对象插入NSMutable数组并将元素移到iOS前面一个位置

时间:2013-11-29 14:06:42

标签: ios objective-c arrays nsmutablearray

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

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

4 个答案:

答案 0 :(得分:3)

假设您知道要插入的索引,只需使用NSMutableArray的{​​{1}}(reference)。在您的情况下,您想要:

insertObject:atIndex:

如果您不知道索引,可以执行this (copy-pasted because nobody likes broken links)

之类的操作
[yourMutableArray insertObject:@(1.5) atIndex:1];

然后,致电:

@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];
}

答案 1 :(得分:1)

两行代码

只需附加该项目,然后对使用时间进行排序或排序,排序实际上非常便宜,几乎 O(n)用于非病理情况。

NSMutableArray *a = [@[@1, @2 ,@3 ,@4] mutableCopy];

// Two lines of code:
[a addObject:@(1.5)];
[a sortUsingSelector:@selector(compare:)];

NSLog(@"a: %@", a);

NSLog oputput:

a: (
   1,
   "1.5",
   2,
   3,
   4
)

以上应为O(log n)

或者,如果您不希望对整个数组进行排序,只需在第一个小于它的条目后插入:

NSUInteger count = [a count];
int index = 0;
while (index < count && [a[index] compare:aNumber] == NSOrderedAscending) {
    index += 1;
}
[a insertObject:aNumber atIndex:index];

以上是O(n)而不是二进制搜索,即O(log n),但对于大多数数组而言,没有有意义的时间差。

答案 2 :(得分:0)

对于您问题中的示例,您可以编写[array insertObject:@(1.5) atIndex:1]

答案 3 :(得分:0)

NSMutableArray * foo = [[NSMutableArray alloc] init];
[foo insertObject:<#(id)#> atIndex:<#(NSUInteger)#>]