0

is this the right way to do the same?

   nsmutablearray *myarray1     //have some data in it
    for (int i=0;i< [myarray1 count]; i++)
    {
          myArray2 = [NSMutableArray array];
         [myArray2 addObject:i];    
    }

and how can i print this value of myarray2.

3
  • are you trying to add element of one array into other array?? Commented May 21, 2010 at 11:54
  • How do you want to print it? Is it just for debugging purpose? Commented May 21, 2010 at 11:54
  • You want to move the myArray2 = [NSMutableArray array]; statement outside the for loop. If you did that, your code would work to copy the array, although Jim's solution with arrayWithArray: is better. Commented May 21, 2010 at 12:09

2 Answers 2

2

If you are trying to copy element of one array to other array then use following code:

 NSMutableArray *secondArray = [NSMutableArray arrayWithArray:firstArray];

If you want to print element value then depending upon data stored in your array you can print element.

i.e if array contains string object then you can print like this:

for(int i=0;i<secondArray.count;i++)
{
     NSLog(@"Element Value : %@",[secondArray objectAtIndex:i]);
}

if array contains any user define object then you can print like this:

for(int i=0;i<secondArray.count;i++)
{
     UserDefineObject *obj = [secondArray objectAtIndex:i];
     NSLog(@"Element Value with property value: %@",obj.property);
}
Sign up to request clarification or add additional context in comments.

Comments

0

The easiest way to create a new array containing the same elements as the old array is to use NSCopying or NSMutableCopying.

NSArray* myArray2 = [myArray1 copy];                // myArray2 is an immutable array
NSMutableArray* myArray3 = [myArray1 mutableCopy];  // myArray3 is an mutable array

If you want to print the contents of an array for debugging purposes:

NSLog(@"myArray2 = %@", myArray2);

If you want prettier printing for a UI, you'll need to iterate through as others have suggested.

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.