1

Hot can I convert an NSMutableString to char *?

e.g.

NSString* someval = @"This is a test.";
NSMutableString *temp = [NSMutableSTring stringWithString:someval];
char * temp2 = ????Not sure what to do here???;
Jesse Naugher
  • 9,780
  • 1
  • 41
  • 56
Keith Adler
  • 20,880
  • 28
  • 119
  • 189
  • 1
    How is the string being mutable relevant? Do you expect to be able to change the `NSMutableString` instance by manipulating the bytes you’d get in `temp2`? –  Nov 02 '11 at 22:45
  • I need to copy the first string because later I will be making changes only to the copy. – Keith Adler Nov 02 '11 at 22:47
  • But do you intend to make these changes via `temp2` or via `temp`? Or, rephrasing it, couldn’t you convert `someval` to `char *` instead of converting `temp` to `char *`? –  Nov 02 '11 at 22:48
  • I am going to use strtok to split up temp2 but I want to make sure someval is never modified. – Keith Adler Nov 02 '11 at 22:52
  • 1) `strtok()` doesn’t change the parsed string; 2) when you get a `char *` representation of an `NSString`, changing it won’t change the original string; 3) take a look at `-[NSString componentsSeparatedByString:]` — you might not even need to use `strtok()`. –  Nov 02 '11 at 22:56

1 Answers1

6

Use the -UTF8String method:

NSString* someval = @"This is a test.";
NSMutableString *temp = [NSMutableString stringWithString:someval];
const char * temp2 = [temp UTF8String];
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • Should I be worried about the warning that it discards qualifiers? – Keith Adler Nov 02 '11 at 22:43
  • 3
    just as an extra (about the memory management of the cstring) From the Apple Docs: The returned C string is automatically freed just as a returned object would be released; you should copy the C string if it needs to store it outside of the autorelease context in which the C string is created. – Jesse Naugher Nov 02 '11 at 22:46
  • @CatManDo If you use my code, it shouldn't give you that. This is likely because in your code, the datatype for `temp2` was `char *` and not `const char *`. – Jacob Relkin Nov 02 '11 at 22:47