views:

776

answers:

4

Hi,

In my own iPhone Application I have used a number of nsstring variables to store values.But sometimes its value become Invalid!!!!Can anybody know what may be the reason? Or tell me about the situation when a nsstring variable becomes Invalid??

Thanks in advance, Syam

A: 

did you copy or retain the NSString ?

+2  A: 

They are being autoreleased. If you create a string using a convenience method (stringWithString, stringWithFormat) it will be added to the autorelease pool.

To stop it being released automatically, sent it a retain message and a release message when you have finished using it so that the memory is released. You can also set up properties to do this semi automatically when you assign the string to a member variable

There are a lot of articles on iPhone (and Mac) memory management here on SO and on the interwebs. Google for autorelease.

Roger Nolan
Ah, you seemed to have beat me to the punch. Anyhow, you probably want "to stop it being -released-dealloced", and properties don't retain/release unless you use self.property = foo instead of property = foo; Might be good to explicitly add that distinction.
lhunath
+3  A: 

NSStrings are also objects. They go by the same memory management rules. If you sin against those rules you will get a pointer to invalid memory and it will look like "invalid" data.

For example:

myString = [NSString stringWithString:@"foo"];

This will create an NSString* that's got autorelease on. When you're assigning it to an ivar that autorelease pool will soon pop putting the retain count back to 0 and dealloc'ing it while you still have a reference to it!

Naughty.

Instead, either retain it or use:

myString = [[NSString alloc] initWithString:@""];

This returns an owning reference. Remember to [myString release]; in dealloc.

This is just one example/case of bad memory management. Read the docs on how to properly manage your object lifecycle. Really.

lhunath
+2  A: 

If this is for a device with fairly limited resources such as the iPhone, you should use [[NSString alloc] init*] over the static convenience methods, as you will put less pressure on the autorelease pool and lower your memory usage. The pool is drained every message loop, so the less objects to enumerate the better.

You should also be aware that autorelease objects in a loop will generate a lot of garbage unless you manage a local autorelease pool.

Stuart Carnie