Objective C Tutorial - Objective-C Data Types






In the Objective-C, we data types to declare variables.

The type of a variable determines how much space it is stored in storage and what kinds of operations we can do on the variables.

The types in Objective-C can be classified as follows:

  • Basic Types:
    includes arithmetic types: integer types and floating-point types.
  • Enumerated types:
  • void typeindicates that no value is available.
  • Derived types:
    include
    • Pointer types,
    • Array types,
    • Structure types,
    • Union types
    • Function types




Integer Types

The following table lists the details about standard integer types with its storage sizes and value ranges:

Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295




Example

To get the exact size of a type, use the sizeof operator.

The following code shows how to get the size of int type.

#import <Foundation/Foundation.h>

int main()
{
   NSLog(@"Storage size for int : %d \n", sizeof(int));
   
   return 0;
}

The code above generates the following result.

Storage size for int : 4

Floating-Point Types

The following table lists the details about float-point types with storage sizes and value ranges and their precision:

Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Example 2

The following example prints storage space used by a float type.

#import <Foundation/Foundation.h>

int main()
{
   NSLog(@"Storage size for float : %d \n", sizeof(float));
   
   return 0;
}

The code above generates the following result.

Storage size for float : 4

Objective-C Type Casting

We can do data type casting to convert a variable from one data type to another data type. The cast operator as follows:

(type_name) expression

The following code does the type casting to floating-point.

#import <Foundation/Foundation.h>

int main()
{
   int sum = 17, count = 5;
   CGFloat mean;

   mean = (CGFloat) sum / count;
   NSLog(@"Value of mean : %f\n", mean );

   return 0;
}

Using Constant

#import <Foundation/Foundation.h>

int main ()
{
  int counter;
  int myAge = 49;
    float myPaycheck = 2222.75;
  for (counter = 0; counter < 3; counter++)
  {
    NSLog (@"This is my age: %i", myAge);
    NSLog (@"This is my paycheck amount: %f", myPaycheck);  
  }
    
    return 0;
}