I have the following code for creating an NSString to contain the body of the text file and then convert it to NSData and output it to a file.
NSString *particleString = [[NSString alloc] initWithFormat:@"%@", @"This is the body of my file"];
NSData *metaVals = [particleString dataUsingEncoding:NSISOLatin1StringEncoding];
Since I have created particleString using alloc, I thought I needed to release it after I have finished converting it to NSData, hence I added
[particleString release];
But my app crashes when I add this line. However, when I remove the line where I use it to create metaVals, I can safely release it.
Can anyone explain why passing it to NSData stops me from releasing it? I believe I own particleString, what’s going on?
According to your comment you do
particleString = [particleString stringByAppendingFormat:@"%@", @"Some other string"];which looses the reference to the original particleString, and replaces it with an autoreleased version. You then go on to release the autoreleased version, causing both a leak of the original particleString, and an overrelease of the new one.Try this
It no longer has a release because both strings are now autoreleased.
I would suggest re-reading the memory management rules