views:

43

answers:

2

Hi everyone,

I'm trying to swap two strings but I'm not sure if what I am doing is legal (coming from java I'm new to the whole retain count memory management).

Here's my code:

NSString *temp = [[NSString alloc] init];
temp = originalLanguageCode;
originalLanguageCode = translatedLanguageCode;
translatedLanguageCode = temp;
[temp release];

Is this allowed? I'm getting some strange bugs and I'm not sure what's causing them, hoping that this might be it. Any help is very appreciated, thanks!

+1  A: 

Everything looks fine except that in your first line you're creating a string which you immediately leak on the second. You can just say:

NSString *temp = originalLanguageCode;
...

... and get rid of the [temp release] since you didn't create (and don't own) the object assigned to "temp."

Now you didn't say whether originalLanguageCode and translatedLanguageCode are instance variables. If so, use their accessors (which should themselves be doing the right thing with memory management).

Joshua Nozzi
+4  A: 

After assigning a newly allocated string to temp you are immediately assigning originalLanguageCode to it, so the allocated string is completely lost. That is a memory leak. Then you are releasing temp, which was originally originalLanguageCode. This is an over-release.

Try this instead:

NSString *temp = originalLanguageCode;
originalLanguageCode = translatedLanguageCode;
translatedLanguageCode = temp;
Cory Kilger
Thanks for the response! I thought I might have been doing something fishy.But then what do i do with *temp? Isn't this now a newly created variable? (which am I right in thinking is a 64 bit UINT? or 32 depending on architecture?)Am I right in thinking then that calling release on temp e.g. [temp release]; affects the actual string object pointed at by temp, and not temp itself (itself being a UINT)? If so what if I am doing this in a long loop as part of some iterative algo, won't I end up with lots of unused pointer variables?Is there anywhere I can learn more about this?
codenoob
@codenoob: `temp` is a pointer to an NSString — you declared it as such in your code (`NSString *temp`). It might be the same size as a 64-bit integer, but that depends on the hardware. And the idea that variables somehow pile up in a loop is just not how it works at all. I'd suggest reading any C book or tutorial for an explanation of how the basic types work.
Chuck