What is the advantage of Arrays in objective C over C-style Arrays

We all know that an Array is the ability of a variable to hold the multiple values at the same time. Objective C supports C-Style way of doing the things and also has its own way which is much better than C.

First Lets talk about the C-style way of playing with  single values  and arrays.

C-style single value declaration and assigning
    
       int singleValue;    
       singleValue = 10; ( the value is stored in the variable named singleValue)

In this case Objective C  claims the memory space that can hold the SingValue and the max it can spare is 4 bytes since we are using int has a datatype.

C-style Arrays

      int multipleValues[3] ;

So here Objective C  claims the memory space that can hold 3 values  and each of 4 bytes maximum. Now you can start assigning values, you have to start from index 0 since in C and Objective C arrays are  Zero based.

         multipleValues[0] = 23;
         multipleValues[1] = 13;
         multipleValues[2] = 34;

or    
    
         multipleValues[3] = {23, 13, 34}

So what if you need to add an element to that array  in the future?

          multipleValues[3] = {23, 13, 34, 77}
Objective C will warn you that you have an excess element in array initializer. This limitation of fixed width is overcome'd in Objective C.

So what if you need to to access the element that you did't claim it before.

          multipleValue[55] = 88;

When you run this, it still works fine so there is no bound checking is done. This works better in Objective C way of doing the thing with NSArray.

So what if you need to mix the types in arrays like ints, floats and bool . C-style of doing the things doesn't let u do that but Objective classes which are added on top of C like NSArray will allow you to do all these things.

No comments:

Post a Comment