Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Labeno

macrumors 6502
Original poster
Jul 21, 2008
351
1,089
I use NSString in a (typedef struct) data structure.
typedef struct {
...
NSTring *name;
...
} MyStruct;

I use calloc() to allocate the structure. When I set the value of the name just once then it shows correctly for the life of the app.

my_struct->name = @"Hello";

If I modify the string using the NSString function stringWithFormat, then the name is correct until the current function completes, then after that, the name contains garbage.

Here's and example of how I modify it.

my_struct->name = [NSString stringWithFormat:mad:"World"];

I can do the following in the beginning of my app, and the corrupted string shows up as soon as the app does any processing outside of the initialization function.

my_struct->name = @"Hello";
my_struct->name = [NSString stringWithFormat:mad:"World"];

but if I do the following, then the string never gets corrupted:

my_struct->name = @"Hello";
my_struct->name = @"World";

I need to use stringWithFormat to create name in different ways.

Any clues as to what the issue is?
Thank you,
Michael
 

Guiyon

macrumors 6502a
Mar 19, 2008
771
4
Cambridge, MA
The output looks corrupted because the stringWithFormat returns an autoreleased string and you are not retaining it.

Code:
[NSString stringWithFormat:@"World"];
causes the resulting string to be autoreleased once it leaves the current scope where as
Code:
my_struct->name = @"Hello";
is a static assignment. If you want long term access to the string (ie: outside of the current function) you can either do:

Code:
my_struct->name = [[NSString stringWithFormat:@"World"] retain];
or
Code:
my_struct->name = [[NSString alloc] initWithFormat:@"World"]

Just remember to perform properly release the string BEFORE calling free() on the structure otherwise you will leak memory.
 

Labeno

macrumors 6502
Original poster
Jul 21, 2008
351
1,089
Thanks!!!

Thank you so much.
I no longer get trashed text, and thank you for the quick education.
 

PhoneyDeveloper

macrumors 68040
Sep 2, 2008
3,114
93
Putting objects into POD structs is a bad idea. Objects and structs use different memory management methods, as you've discovered. Do you now release the string when the struct is freed?

Better is to use an NSObject subclass for this purpose. It uses the same memory management as the NSString and it will be simpler to avoid memory leaks and under-retained objects.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.