views:

576

answers:

2

I'm having a hell of a time understanding pointers in Objective C. They don't behave like I would assume based on various C tutorials.

Example:

// Define Name and ID
NSString *processName = [[NSProcessInfo processInfo] processName];
NSNumber *processID = [NSNumber numberWithInt:[[NSProcessInfo processInfo] processIdentifier]];

// Print Name and ID
NSLog(@"Process Name: %@  Process Identifier: %@", processName, processID);

As I understand it, processName is a pointer to an object of type NSString. processID is a pointer to an object of type NSNumber. When both are called in NSLog(), they do not have an asterisk preceding their name and therefore should be returning pointer values. Why is there no 'address of' character in Obj C? Why does this code work?

Thank you for your time.

+7  A: 

The %@ in your format string tells NSLog to call -description on the relevant object and use that string for its' display value. If you do want the address of the pointer you should use %x or %qx on 64-bit.

Ashley Clark
Or use %p, which prints a pointer address with a nicer format for pointers.
mipadi
+10  A: 

Objects in objective c are represented as pointers to c structures that contain all of the object data. If the object were an actual struct (rather than a pointer to one) it would make things like passing objects as method parameters much less efficient. So once you initialize an object:

NSString *aString = /* initial value */;

you will almost always just use the pointer aString, rather than dereferencing it (i.e. *aString).

The %@ token in the NSLog() function expects a pointer type and will call the description method on that object to determine what value to output. When the description method is called on an NSString object, it returns the receiver, so the %@ token is replaced by the contents of the string in the output.

dvenema