Difference between NSArray and NSMutable Array

后端 未结 5 1525
北海茫月
北海茫月 2021-01-07 04:44

hi am working with NSArrays using foundation tool and i have wrote the following code

    -(void)simplearrays
{
 NSMutableArray *arr = [NSMutableArray array         


        
5条回答
  •  再見小時候
    2021-01-07 05:19

    Cocoa arrays are not C arrays. They are container objects with some similarities to Java vectors and array lists.

    You cannot add objects or retrieve them using the C subscript syntax, you need to send messages to the object.

    -(void)simplearrays
    {
        NSMutableArray *arr = [NSMutableArray array]; 
        // arrayWithCapacity: just gives a hint as to how big the array might become.  It always starts out as
        // size 0.
    
        for(int i =0;i<3;i++)
        {
            int input;
            scanf("%d",&input);
            [array addObject: [NSNumber numberWithInt: input]];
            // You can't add primitive C types to an NSMutableArray.  You need to box them
            // with an Objective-C object
        }
        for(int j =0; j<3;j++)
        {
           printf("\n%d", [[arr objectAtIndex: j] intValue]);
           // Similarly you need to unbox C types when you retrieve them
        }
        // An alternative to the above loop is to use fast enumeration.  This will be
        // faster because you effectively 'batch up' the accesses to the elements
        for (NSNumber* aNumber in arr)
        {
           printf("\n%d", [aNumber intValue]);
        }
    }
    

提交回复
热议问题