lmirosevic
lmirosevic

Reputation: 16317

how do i swap two NSString variables (in a non garbage collected environment)?

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!

Upvotes: 0

Views: 600

Answers (2)

Cory Kilger
Cory Kilger

Reputation: 13044

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;

Upvotes: 5

Joshua Nozzi
Joshua Nozzi

Reputation: 61228

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).

Upvotes: 1

Related Questions