简体   繁体   中英

Why does a string pointer in Objective-C accept and return the value of the string and not a memory address?

For example in this code:

NSString *greeting = @"Hello";
NSLog(@"Greeting message: %@\n", greeting );

Greeting takes the value of a string, not an address. It also displays a string in NSLog and not an address. However, I thought pointers were supposed to be used like this:

int  var = 20;   /* actual variable declaration */
int  *ip;        /* pointer variable declaration */

ip = &var;  /* store address of var in pointer variable*/

NSLog(@"Address of var variable: %x\n", &var  );

/* address stored in pointer variable */
NSLog(@"Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */
NSLog(@"Value of *ip variable: %d\n", *ip );

return 0;

I've always wondered why it's okay to do this with string pointers.

Well, that is something called Syntactic Sugar . What we are actually seeing; exactly doesn't happen like that under the hood.

For example, the code you have written:

NSString *greeting = @"Hello";
NSLog(@"Greeting message: %@\n", greeting );

When you pass greeting into NSLog, actually the following line of code gets executed.

NSLog(@"Greeting message: %@\n", [greeting description]); // description is a method defined in NSObject and NSString inherits it.

And even if you do:

NSString *greeting = @"Hello";

Now, greeting variable doesn't hold the contents of the string, neither it can because it is a pointer. It just holds the address of NSString @"Hello" where it is stored. And again, the assignment of pointer happens under the hood. The same is the case with the C language; we can write the following code in C, and it will compile without any errors:

char *string = "Hello, world!"; 

In C, the string "Hello, world!" is basically a character array, and string variable actually stores the pointer to this character array.

If you see the definition of NSLog method, it looks something like this:

FOUNDATION_EXPORT void NSLog(NSString *format, ...) NS_FORMAT_FUNCTION(1,2);

It clearly shows that NSLog message receives an NSString pointer. But what do we actually pass? We pass the NSString in it, but what is actually passed is a pointer to that NSString, again under the hood :)

I hope this helps you.

%@ is the string formatter for NSObject s, calling the objects -description method. If you want the pointer address of the string object try %p .

NSString *string = @"A string";
NSLog(@"Object contents: %@", string);
NSLog(@"Object address: %p", string);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM