Sreelal
Sreelal

Reputation: 785

Sometimes NSString becomes Invalid?

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

Upvotes: 1

Views: 1179

Answers (5)

Dmitry
Dmitry

Reputation: 14622

I asked the same question. And the following answer was the best of convenience. Just use:

[myString retain];

And then in dealloc method (e.g. viewDidUnload):

[myString release];

Upvotes: 0

Stuart Carnie
Stuart Carnie

Reputation: 5476

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.

Upvotes: 2

lhunath
lhunath

Reputation: 125406

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.

Upvotes: 4

Rog
Rog

Reputation: 17170

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.

Upvotes: 2

softboysxp
softboysxp

Reputation:

did you copy or retain the NSString ?

Upvotes: 0

Related Questions