I am trying to get rid of some confusion when working with C.
Is using char *name
in some sense the same as working with NSString *name
in the sense that the pointer still points to the first memory allocation for it?
Ofcourse NSString
has a bunch of extras but that isnt what I mean, will working with char *name
allow me to work as if it was a NSString *name
, so that I could in the future just work with the pointer "name" ?
The answer is no.
char*
is meant to point to a simple array of (or single) char
data values.
char* myCharPtr = "This is a string.";
//In memory: myCharPtr contains an address, e.g. |0x27648164|
//at address 0x27648164: |T|h|i|s| |i|s| |a| |s|t|r|i|n|g|.|\0|
On the other hand, NSString *name
will be a pointer to an object which could have lots of extras, and you can't rely on where the actual character data is stored, or how. It is not encoded as ASCII (Sherm Pendley down below said it's UTF-16), and it could have extra data like the string's length, etc.
NSString* myStringPtr = @"This is an NSString.";
//In memory: myStringPtr contains e.g. |0x27648164|
//at address 0x27648164: |Object data|length|You don't know what else|UTF-16 data|etc.|
You alter and access unknown objects through their exposed methods because you don't know how they are formatted in memory, and thus can't access their data directly. (Or because they encapsulate themselves to hide it from you.)
You can still use the NSString
pointer in future if you declare it as NSString *name
though. This is what I mean:
NSString *name = @"This is a string.";
NSString *sameName = name; //This is pointing to the same object as name
NSLog(@"%@", sameName); //This prints "This is a string.", and if NSStrings were mutable, changing it would change name as well.
//They point to the same object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With