uttam
uttam

Reputation: 1364

how to add the element in the array using the for loop in objective-c?

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.

Upvotes: 0

Views: 1201

Answers (2)

JeremyP
JeremyP

Reputation: 86651

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.

Upvotes: 0

Jim
Jim

Reputation: 4719

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);
}

Upvotes: 2

Related Questions