简体   繁体   中英

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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM