Trouble with NSString

Discussion in 'iOS Programming' started by Labeno, Oct 22, 2008.

  1. Labeno macrumors regular

    Labeno

    Joined:
    Jul 21, 2008
    #1
    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
     
  2. Guiyon macrumors 6502a

    Joined:
    Mar 19, 2008
    Location:
    North Shore, MA
    #2
    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.
     
  3. Labeno thread starter macrumors regular

    Labeno

    Joined:
    Jul 21, 2008
    #3
    Thanks!!!

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

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #4
    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.
     

Share This Page