Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Object to Unallocated Pointer

Let's say that I have declared an NSString like this

NSString *myString = [[NSString alloc] initWithString:@"Never Heard"];
NSString *tempString;

tempString = myString;

[myString release];

My question is why does it work? As you can see, I didn't alloc for the tempString. Therefore I don't think there is a need to release it. But if I try to alloc and init the tempString, it will bring an error.

NSString *myString = [[NSString alloc] initWithString:@"Never Heard"];
NSString *tempString = [[NSString alloc] init];

tempString = myString;

[myString release];

I use NSString as example, but instead I have different classes implemented. I'm trying to emphasize how memory allocation works here. Care to clarify and explain?

like image 776
sayzlim Avatar asked Apr 13 '26 16:04

sayzlim


2 Answers

A pointer is simply a memory address. You only create one object, and then you point tempString to that object. And tempString == myString.

[myString release] deallocates the string, leaving both pointers pointing at deallocated memory.

Do no confuse variables with objects. Variables are simply are handles that you use to access objects. Creating a new variable does not mean you are creating a new object.

like image 171
Alex Wayne Avatar answered Apr 15 '26 05:04

Alex Wayne


This is absolutely not about memory allocation. This is all about how pointers work. When you do this:

tempString = myString;

tempString points to the same object as myString. So calling any method on tempString is the same as calling them on myString.

like image 30
Max Avatar answered Apr 15 '26 04:04

Max



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!