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?
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.
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.
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