0

I am initializes NSMutableArray with 4 object.Then I am adding 2 more object in it after the first index. Then I am deleting that two new added objects. From theory it is clear that after all operation i will get the original array back that i have created first, but after deleting objects i am getting strange result.

CODE :-

- (void)viewDidLoad
{
    [super viewDidLoad];
   NSMutableArray *arr = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4", nil];

    for (NSString *str in arr)
    {
        NSLog(@"%@",str);
    }

    [arr insertObject:@"1.1" atIndex:1];
    [arr insertObject:@"1.2" atIndex:2];

    for (NSString *str in arr)
    {
        NSLog(@"New %@",str);
    }

    [arr removeObjectAtIndex:1];
    [arr removeObjectAtIndex:2];

    for (NSString *str in arr)
    {
        NSLog(@"Old %@",str);
    }
}

OUTPUT :-

2013-12-28 14:42:02.703 ArrayDemo[1687:11303] 1
2013-12-28 14:42:02.704 ArrayDemo[1687:11303] 2
2013-12-28 14:42:02.705 ArrayDemo[1687:11303] 3
2013-12-28 14:42:02.705 ArrayDemo[1687:11303] 4
2013-12-28 14:42:02.705 ArrayDemo[1687:11303] New 1
2013-12-28 14:42:02.706 ArrayDemo[1687:11303] New 1.1
2013-12-28 14:42:02.706 ArrayDemo[1687:11303] New 1.2
2013-12-28 14:42:02.706 ArrayDemo[1687:11303] New 2
2013-12-28 14:42:02.707 ArrayDemo[1687:11303] New 3
2013-12-28 14:42:02.707 ArrayDemo[1687:11303] New 4
2013-12-28 14:42:02.708 ArrayDemo[1687:11303] Old 1
2013-12-28 14:42:02.708 ArrayDemo[1687:11303] Old 1.2
2013-12-28 14:42:02.709 ArrayDemo[1687:11303] Old 3
2013-12-28 14:42:02.710 ArrayDemo[1687:11303] Old 4

I am not able to understand why this happening ??? Do anyone knows about it ?? Any help will be appreciated...

Thanks in advance....

1 Answer 1

2

Initial array:

    1, 2, 3, 4

After [arr insertObject:@"1.1" atIndex:1]:

    1, 1.1, 2, 3, 4

After [arr insertObject:@"1.2" atIndex:2]:

    1, 1.1, 1.2, 2, 3, 4

After [arr removeObjectAtIndex:1]:

    1, 1.2, 2, 3, 4

After [arr removeObjectAtIndex:2]

    1, 1.2, 3, 4

So everything is correct. If you want to remove the elements that you inserted earlier, then you have to remove them in reverse order:

[arr removeObjectAtIndex:2];
[arr removeObjectAtIndex:1];

In this case, the final result would be 1, 2, 3, 4 again.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.