Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C /NSObject pointers compared to C pointers

According to apples objective-c documentation, the NSObjects use C-pointers to keep track of them. I am fairly new to iOS and comparing the pointer operations on NSObjects with C pointers gets confusing. For example:

NSString *string1 = @"This is a string";
NSString *string2;
string2 = string 1;

In C, (correct me if I am wrong please) this = b/w 2 pointers makes them point to the same "pointee". This means that changing string1 should also change string2. But it doesn't seem to work like this, and NSStrings are strictly immutable anyways so this adds a bit of confusion.

string1 = @"new string";

If these pointers operate like C pointers, than shouldn't this change string2 since it points to the same place as string1. Also, in C, a pointer must be assigned to a pointee before it can be dereferenced. This rule does not seem to apply to NSObjects. What is the '@' doing? Finally, why don't I ever see dereferencing with NSObjects happening like:

*string1 = @"modifying the string"; //shouldn't this be how to access the contents of the pointer string1 if it operates like a c pointer?

Could someone shed some light on what is going on under the hood of Objective-C pointers and how they compare and contrast to C pointers? Any help would be greatly appreciated.

like image 666
andypf Avatar asked Mar 24 '26 04:03

andypf


1 Answers

You would get the same behavior in C as in Objective-C: if you do this

char *a = "hello";
char *b = a;
b = "world";

then a is not going to change. The changes made to a common object pointed to by multiple pointers become visible when the object is mutable. Neither NSString nor C string literals are mutable, so let's construct a different example:

NSMutableString *string1 = [NSMutableString string:@"This is a string"];
NSMutableString *string2;
string2 = string1;
NSLog(string1);
NSLog(string2);
[string1 appendString:@" (a very long one!)"];
NSLog(string1);
NSLog(string2);

Now string2 "sees" the changes made to string1, because the object is mutable.

A similar example in C would look like this:

char[] a = "hello";
char b = a;
printf("%s %s\n", a, b);
strcpy(b, "world");
printf("%s %s\n", a, b);
like image 198
Sergey Kalinichenko Avatar answered Mar 25 '26 16:03

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!