0

I want to append an object in an array.

For example,

 NSMutableArray *array = [[NSMutableArray alloc]init];
    for (int i=0; i<5; i++)
    {
        [array addObject:@[@"Any"]];
    }

It gives an output like this:

array: (
        (
        Any
    ),
        (
        Any
    ),
        (
        Any
    ),
        (
        Any
    ),
        (
        Any
    )
)

Now I want to append object at index 3 of an array so that it could appear like below:

array: (
            (
            Any
        ),
            (
            Any
        ),
            (
            Any
        ),
            (
            Any, Where, How, When
        ),
            (
            Any
        )
    )
1
  • It is index 2, not index 3. Commented Apr 25, 2014 at 14:08

3 Answers 3

1

Use function insertObjectAtIndex to achieve it.

[array insertObject:anObject atIndex:2];

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

1 Comment

This gives an output like this: array: ((Any),(Any),(Any),(Any),Where, How, When,(Any)). However, I want Where, How, When, inside the braces with Any like: (Any, Where, How, When )
1

If I understand you...

[array replaceObjectAtIndex:2 withObject:@[[[array objectAtIndex:2] firstObject],@"Where",@"How",@"When"]];

2 Comments

Are you sure that you typed correctly? This does exactly what you asked for.
@Desdenova Not exactly, to be honest ))) but I edited
0

Try this:

NSMutableArray *array = [NSMutableArray new];
for (int i=0; i<5; i++)
{
    [array addObject:[NSMutableArray arrayWithObject:@"Any"]];
}
NSLog(@"%@", array);

NSMutableArray *subArray = [array objectAtIndex:3];
[subArray addObjectsFromArray:@[@"Where", @"How", @"When"]];
NSLog(@"%@", array);

Note, @[] creates an instance of NSArray class which cannot be modified later. You can modify only instances of NSMutableArray class.

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.