Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How pointers work in Objective-C

I have a quick question about how pointers work in Objective C.

In C we have:

int a = 1;
int *b;
b = &a;
//b is 1.

But in Objective C everything is already a pointer. So if we have:

NSString *a = @"String";
NSString *b;
b = a;         //I know this syntax is wrong but please bear with me.

will b equal "String"? Or will b point to a, which holds the value "String"?

Thanks in advance for your help!

like image 753
Seslyn Avatar asked Apr 29 '26 08:04

Seslyn


2 Answers

B and A will both point to the same memory address which holds the actual String "String".

To clarify, if you compile and run this:

NSString *a = @"String";
NSString *b;
b = a;

NSLog(@"A is %@ %p",a,a);
NSLog(@"B is %@ %p",b,b);

The output is:

2015-03-26 21:35:09.860 ObjCTest[1379:187000] A is String 0x100b25068

2015-03-26 21:35:09.860 ObjCTest[1379:187000] B is String 0x100b25068

I literally ran this code now, and the output shows that both A and B point to the same NSString object - which is at memory location 0x100b25068, and contains the value "String".

like image 83
Woodstock Avatar answered Apr 30 '26 20:04

Woodstock


In C we have:

int a = 1;
int *b;
b = &a;
//b is 1.

Actually, *b == 1. b is the memory address of a (which is what &a means).

But in Objective C everything is already a pointer. So if we have:

NSString *a = @"String";
NSString *b;
b = a;         //I know this syntax is wrong but please bear with me.

will b equal "String"? Or will b point to a, which holds the value "String"?

b and a point to the same NSString object, similar to how C works.

like image 30
Mike DeSimone Avatar answered Apr 30 '26 22:04

Mike DeSimone



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!