views:

1280

answers:

1

I am having trouble assigning the value of an NSString to a char * within a structure of a singleton class. The following is a simplification of my problem. My code utilizes more fields in the structure and passes more NSStrings.

Say I have a singleton class "SingletonClass" with a structure (I've done my homework with the Apple Documentation and implemented it correctly):

struct sampleStruct {
    char *string1;
    //other fields
} struct1;

with this method that sets the value of struct1.string1 to the NSString that was passed:

- (void)initStructWithString:(NSString *)inputString {
     //warning: assignment discards qualifiers from pointer target type
     struct1.string1 = [inputString cStringUsingEncoding:NSUTF8StringEncoding];
}

and this method that uses struct1.string1:

- (void)useCharArray {
     //I would obviously be doing something more complex in reality
     printf("This is the char array: %s", struct1.string1);
     //doesn't print the value I assigned to it, but garbage
}

When I call initStructWithString:(NSString *)inputString from one class and try to call useCharArray from another class struct1.string1 is a bunch of garbage. During debugging I've confirmed that each class is getting the same instance of this SingletonClass.

I'm still learning Objective-C as well as C along the way, so I'm aware it could be a problem with my memory management. I know I [NSString cStringUsingEncoding] should be assigned to a const char * and not a char *, but I don't know how else to go about it since the field in the structure is a char *. I've tried other approaches within initSructWithString such as assigning a new const char * the result of [NSString cStringUsingEncoding] and then copying that with strlcpy to struct1.string1. That approach had the same result.

What is the correct technique for storing the value of an NSString in a char * within a struct and how can I ensure that the fields within this struct retain their value as the SingletonClass is used by different classes?

+3  A: 

One thing worth noting is that the correct method name would be cStringUsingEncoding:; and that this string disappears roughly at the same time inputString does, so the resulting string will have to be copied.

It might also be worth exploring the use of UTF8String instead (a convenience method that does the same).

Williham Totland
Thanks for the correction and explanation. So when you say copy, am I looking at using memcpy since something like strlcpy will copy a pointer to a string that will disappear?
Eric de Araujo
using memcpy is always a good idea; but you also need to allocate the target buffer before copying; so that you actually have some malloced memory to copy the string into.
Williham Totland