views:

42

answers:

2

Hi guys,

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?

+3  A: 

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

NSString *particleString = [NSString stringWithFormat:@"%@", @"This is the body of my file"];
particleString = [particleString stringByAppendingFormat:@"%@", @"Some other string"]; 
NSData *metaVals = [particleString dataUsingEncoding:NSISOLatin1StringEncoding]; 

It no longer has a release because both strings are now autoreleased.

I would suggest re-reading the memory management rules

Joshua Weinberg
Thank you very much. That was really helpful.
ar106
+1  A: 
[particleString stringByAppendingFormat:@"%@", @"Some other string"];

this returns a newly created object. which means the first object created and assigned to particleString is leaking, and you are trying to release the newly, autoreleased, object that has been created by using the -stringByAppendingFormat: method

You could probably use a NSMutableString instead which has a method named appendFormat:(NSString *)...

Pier-Olivier Thibault
Joshua Weinberg's answer is an equally good answer. I suggest you use whatever you are most comfortable with.
Pier-Olivier Thibault
Excellent. Thank you very much.
ar106