I'm pretty new to C and Objective C, however I can't find this answer
So I ran into a problem that took me a while to work out, basically I was told that when ever you alloc an object you should release it. So that is what I did and it caused my program to crash...
Here is the code:
NSString *numberString = [[NSString alloc] init];
numberString = resultLabel.text;
[self setFirstNumber:[numberString doubleValue]];
[resultLabel setText:@"0"];
[numberString release];
I think I figured out why it's because of the "numberString = resultLabel.text" line, however I don't understand why the program crashes. Why can't I release numberString? Will it cause a memory leak if I don't?
P.S. I know the code is clumsy, I'm a newbie to programming and a even more super newbie to Objective C.
P.S.S. I release resultLabel later on in the -(void)dealloc{}
numberString is a pointer which means it will point to the memory that you assign it. On the first line yes you did call alloc/init and you are responsible for releasing it. On the next line though you set the pointer to another value that you do not own and the original string you called alloc on is getting leaked. A call to [[NSString alloc] init]
is quite pointless but here is your example working with release.
NSString *numberString = [[NSString alloc] init]; //Not necessary
[numberString release]; //Properly released now it is safe to reassign
numberString = resultLabel.text;
//numberString is now pointing at another object
[self setFirstNumber:[numberString doubleValue]];
[resultLabel setText:@"0"];
//No need to release it any more here
What you will want to do is just set numberString to the text and not use any release calls.
NSString *numberString = resultLabel.text;