Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 38 ยท Language Basics

Variables and Data Types

Learn Objective-C primitive types, NSInteger and CGFloat, BOOL, object pointers, id, nil and type casting, with sizes, ranges and common pitfalls explained.

Objective-C has two kinds of types. The first kind is every type from C: int, char, double and so on. These are plain values stored directly in a variable. The second kind is objects, which live on the heap and are always accessed through a pointer such as NSString *. Knowing which kind you are holding explains most of the language's rules about assignment, comparison and printing.

Declaring variables

A variable declaration gives a type, a name and, optionally, an initial value:

OBJECTIVEC
int age = 30;
double price = 19.99;
char grade = 'A';
NSString *title = @"Objective-C";

Local variables must be given a value before use. A local int that is not initialized holds garbage. An object pointer local variable is different: under ARC it is automatically set to nil if you do not initialize it.

Names start with a letter or underscore, are case sensitive, and by convention use lowerCamelCase.

The primitive types

Type Typical size Example
char 1 byte 'A'
short 2 bytes short s = -5;
int 4 bytes int n = 100;
long 8 bytes (64-bit Apple platforms) long big = 1L << 40;
long long 8 bytes long long x = 9000000000LL;
float 4 bytes float f = 1.5f;
double 8 bytes double d = 3.14159;
unsigned int 4 bytes unsigned int u = 7u;

Sizes come from C and can vary by platform, so use sizeof to check them (the first stand-in below does exactly that).

Foundation adds a few platform-friendly types that you will see constantly in Cocoa APIs:

  • NSInteger is a signed integer that matches the machine word (long on 64-bit, int on 32-bit).
  • NSUInteger is its unsigned twin, used for counts and indexes such as [array count].
  • CGFloat is double on 64-bit and float on 32-bit; used for geometry.
  • BOOL holds YES or NO.
OBJECTIVEC
NSInteger score = -12;
NSUInteger count = 5;
CGFloat width = 120.5;
BOOL isReady = YES;

BOOL, YES and NO

BOOL is a typedef of a small integer (a real C bool on modern 64-bit Apple platforms, a signed char on older ones). YES is 1 and NO is 0. Prefer writing if (isReady) over if (isReady == YES): because any non-zero value is true in C, comparing against YES fails if a function returns 2, which is a real bug source with older APIs.

C also offers bool, true and false from <stdbool.h>. They work in Objective-C, but Cocoa APIs use BOOL, so stay with it in Objective-C code.

Object pointers, id and nil

Objects are accessed through pointers. The * is part of the declaration:

OBJECTIVEC
NSString *name = @"Ada";
NSArray *list = @[@1, @2, @3];

Two special names complete the picture:

  • id is a pointer to any object. No * is needed: id thing = @"text";. It turns off compile-time checking of which messages the object understands, so use it only when you need to hold objects of different classes.
  • nil is the null object pointer. Sending any message to nil is allowed and does nothing: it returns nil, 0 or NO. Pointers to C types use NULL, and class pointers use Nil.
OBJECTIVEC
NSString *missing = nil;
NSUInteger len = [missing length];   // 0, no crash

This is very different from C or Java, where calling a method on a null pointer crashes. It makes code shorter, but it can also hide bugs when a value silently becomes nil.

Type conversion and casting

Mixing types in arithmetic converts them automatically. int and double give a double. Integer division truncates:

OBJECTIVEC
int a = 7, b = 2;
double wrong = a / b;           // 3.0 (integer division happens first)
double right = (double)a / b;   // 3.5

A cast such as (double)a tells the compiler to convert explicitly. Casting between object types with (NSString *)thing does not convert the object, it only changes what the compiler believes. Wrong casts crash at run time.

Converting between numbers and strings uses methods, not casts:

OBJECTIVEC
NSInteger n = [@"42" integerValue];
NSString *text = [NSString stringWithFormat:@"%ld", (long)n];

Stand-in: sizes and ranges

The C types behave identically in Objective-C. This program prints each size and the limits from <limits.h>:

C Stand-in (C): sizes of the primitive types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The pointer size is the key to NSInteger: on a 64-bit machine pointers and long are 8 bytes, so NSInteger is 8 bytes there too.

Stand-in: division and casting

C Stand-in (C): integer division and casts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The last line demonstrates why comparing a flag with YES (1) can fail when the value is 2 but still "true".

Common mistakes

  • Printing an NSInteger with %d. Cast to long and use %ld.
  • Comparing objects with ==. That compares addresses, not content. Use isEqual: or isEqualToString: (see Operators and Expressions).
  • Putting a C struct or primitive into an NSArray. Collections hold only objects, so you must box numbers; see Literals and Boxing.
  • Declaring NSString name without *. Objects are always pointers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does [nil length] evaluate to?

    Messages to nil are legal and return a zero value of the return type.
  2. 2. Which type is recommended for the count of items in an array?

    NSUInteger matches the machine word size and is what [array count] returns.
  3. 3. What does id mean?

    id can hold any object pointer, and the * is not written.
  4. 4. What is the value of 7 / 2 when both are int?

    Integer division truncates toward zero, so the result is 3.
  5. 5. Why is if (flag) safer than if (flag == YES)?

    If a legacy API returns a non-zero value other than 1, the comparison with YES is false even though the value is true.

Summary

  • C primitive types (int, double, char, ...) are stored by value; objects are stored through pointers.
  • Use NSInteger, NSUInteger, CGFloat and BOOL in Cocoa-facing code.
  • id holds any object; nil is the empty object pointer and absorbs messages safely.
  • Integer division truncates; cast to double before dividing to keep fractions.
  • Cast NSInteger to long when formatting.

Next: Operators and Expressions