Objects, pointers and getting the data


#1

There’s one thing that I don’t understand when using pointers.

Code for reading the int value that is stored at an address:

int i = 5;

// Storing the address of variable i in pointer *ptr
int *ptr = &i;

// By using the * I read the int value that is stored at the address stored in ptr
printf("%d\n", *ptr);

When using objects and I would use the following code to read the value that is stored at an address:

NSDate *now = [NSDate date];
NSLog(@"The date is %@", now);

My question is the following. Why don’t I have to write the following code:

In this case I also want to read the value that is stored at an address. So why don’t I have to use the asterisk?

I hope that you guys can help me out with this. Thanks in advance!


#2

Your question is quite valid.

There are 10 cases to consider here: the case of a simple object (an instance of an int) and the case of a complex object (an instance of an NSDate - an Objective-C object.)
(By the way, 10 is in base 2.)

Case 01:

int i = 5;

// Storing the address of variable i in pointer *ptr
int *ptr = &i;

// By using the * I read the int value that is stored at the address stored in ptr
printf ("%d\n", *ptr);

Case 10:

NSDate *now = [NSDate date];
NSLog(@"The date is %@", now);

NSLog(@"The date is %@", *now);

In the first case, the pointer points to a simple object in memory; it points to an instance of an int. Thus we can access this simple object through the pointer by reading the data, sizeof (int) (or sizeof (*int)) bytes long, starting at the address stored in the variable ptr. The expression *ptr is valid and stands for this object (an int) which can be printed using the printf statement printf ("%d\n", *ptr) because an integer can be printed using the printf statement printf ("%d\n", anInteger).

In the second case, the pointer points to a complex object (an Objective-C object) and thus the expression *now is invalid; the contents of an Objective-C object can’t be accessed using the derefrencing operator.

To see what error message Xcode displays, try this piece of code:

NSDate *now = [NSDate date];

// Expression *now is not valid!
NSLog (@"The date is %@", *now);
NSDate now2 = *now;

Because the expression *ptr is not a valid expression in Objective-C when ptr points an Objective-C object, you can’t do this:

NSDate *now = [NSDate date];
NSLog (@"The date is %@", *now);

Summary:

  • Pointer to simple objects (all objects of fundamental types and all objects of user defined types containing only simple objects) can be derefrenced with the * operator.
  • Complex Objective-C objects can’t be derefrenced with the * operator.

#3

Thanks for the answer ibex10. I understand it for 100% now. Thanks!!!