Quote:
Originally Posted by zv77rus@gmail.com
so if I want to create an object NSString, I do the following:
NSString *newText = [[NSString alloc] initWithFormat:@"%d", someNum]
I assume, the object is allocated on the heap. So if I want to delete it, I will do the following:
[newText release];
But what if I use the following code:
NSString *newText = [NSString stringWithFormat: @"%d", someNum];
Is it allocated in the stack? is [NSString stringWithFormat: @"%d", someNum] created locally and will be automatically deleted when out of scope? Why is the following line gives me an error when I am trying to delete the object in this case created in the previous example?
[newText release];
Please, help. Thanks!
|
Becuase when you stored the object in the 'newText' pointer, you retained it by using 'alloc'. That means you're responsible for it's release.
In the second Line of your code, you used a Class method that did almost the same thing but what you don't see is that it also does a 'autorelease' on your object and as such it is released and you do not need to release it. Doing so will result in a crash.
The second line is the equivalent to 'NSString *newText = [[[NSString alloc]initWithWhatever...]autorelease];'
it does all that in the 'stringWithFormat' method that works on the NSString class. Obviously the 'stringWithFormat' is a class method.