Monday, September 9, 2013

Pointers in Objective C

A pointer references a location in the memory. In simple words it keeps the address of the memory where actual data is stored. Obtaining the content of the pointer is called deferencing the pointer.
Pointers to data significantly improve performance for repetitive operations such as traversing strings, lookup
tables, control tables and tree structures. In particular, it is often much cheaper in time and space to copy and dereference pointers than it is to copy and access the data to which the pointers point. you can learn more about pointers here.

We will discuss what are different operations on pointer which you should take care while programming in objective C. I hope after reading this blog it would be easier for you do perform different operations and understanding Pointers.

What is nil pointer?
Objective C has nothing like null unlike other programming language. Where if you want to say this object holds  nothing you set it to Null and when you try to access that object..Boomm.. Code just crashes with some exception

generally "Object reference not set to an instance of an object." [Common error for few high level language..:P]. So how do we handle this scenario in Objective-C? We have something call nil. If we want an object to set to nothing we set it to nil. nil means 0. If you send a message to a nil pointer it does nothing an return nil. code just runs without any exception.

NSstring *str = nil;

Pointer arithmetic:
You can perform a limited number of arithmetic operations on pointers. These operations are:

  • Increment and decrement
  • Addition and subtraction
  • Comparison
  • Assignment.

However while comparison one should take care that doing == operation on two pointers will compare the address stored in the pointers on the actual content. for this operation Objective C provide a method isEqualToString.

The following will actually compare the string values:
if([name isEqualToString:firstName])

in Objective C there is another better way for string comparison

NSString *name = @"Name";
NSString *firstName = @"namE";

if ([name caseInsensitiveCompare:firstName] == NSOrderedSame) {
    //strings are same
} else {
    //strings are not same

These are some basics of pointers and few highlights of Objective C String pointers and nil pointer.


  1. Can above code executed on linux platform? Would i need to include some header?

  2. Sanjiv, At this stage I am not sure about this. However i will look into it and will update you.

    Thanks for asking.