0

I am trying to add NSMutableArray in another NSMutableArray. But what I am trying to do is nested arrays.

My current code is:

  NSMutableArray *array1 = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
  NSMutableArray *array2 =[[NSMutableArray alloc] init];
  [array2 addObject:array1];

This code is adding 4 objects in array2 but I want it to add array1 as single object.

Edit: This code is working I know but in my case in XCode something is wrong with initializing and it is adding 4 objects. I still could not figure it out. So this piece of code is working properly. So the problem was about initialization in a for loop.

4
  • You might need to use NSDictionary for what you are expecting. When you assign array to an array, the result will be the same. Commented Jun 19, 2014 at 6:35
  • are you sure its adding 4 objects in array2 ? as the code working fine for me, try logging count of array2. Commented Jun 19, 2014 at 6:44
  • Your code is correct. Commented Jun 19, 2014 at 6:52
  • nothing wrong with your code if you want to add array1 as single object. Commented Jun 19, 2014 at 6:57

3 Answers 3

3

I copy/pasted your code, and it adds one object to array2, not four.

Printing description of array2:
<__NSArrayM 0xc46c7b0>(  <-- THIS ARRAY HAS 1 OBJECT
    <__NSArrayM 0xc488770>( <-- THIS ARRAY HAS 4 OBJECTS
        Red,
        Green,
        Blue,
        Yellow
    )
)

You may be are getting confused by the fact that printing the description, prints the contents of the inner array also.

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

1 Comment

The problem was about initialization in a for loop.I have edited the question description also. Thanks!
0

Try:

NSMutableArray *array2 =[[NSMutableArray alloc] initWithArray:array1];

12 Comments

is this working with adding many arrays? I mean I will add array3,array4,array5 ... to array2.
Yes it does. Try: [array2 addObject: array3]; [array2 addObject: array4];
This is not different at all from the original question. It is incorrect
this answer will confuse other people in the future. The reason it works is not the change he suggested.
Start a new project and copy paste this code. Tell me if that persists
|
0

i am using this and its working

NSArray *array1 = @[array2, array3, ...];

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.