2011-11-02 31 views
0

热我可以转换一个NSMutableString char *?NSMutableString char *

例如

NSString* someval = @"This is a test."; 
NSMutableString *temp = [NSMutableSTring stringWithString:someval]; 
char * temp2 = ????Not sure what to do here???; 
+1

是如何串是可变的相关性?你是否希望能够通过处理'temp2'中的字节来更改'NSMutableString'实例? – 2011-11-02 22:45:20

+0

我需要复制第一个字符串,因为稍后我将仅对该副本进行更改。 –

+0

但是你打算通过'temp2'或者通过'temp'做出这些改变吗?或者,改写它,你能不能将'someval'转换为'char *'而不是将'temp'转换为'char *'? – 2011-11-02 22:48:56

回答

5

使用-UTF8String方法:

NSString* someval = @"This is a test."; 
NSMutableString *temp = [NSMutableString stringWithString:someval]; 
const char * temp2 = [temp UTF8String]; 
+0

我应该担心它会丢弃限定符吗? –

+3

就像一个额外的(关于cstring的内存管理)从Apple Docs:返回的C字符串会自动释放,就像释放一个返回的对象一样;如果需要将C字符串存储在创建C字符串的autorelease上下文之外,则应复制C字符串。 –

+0

@CatManDo如果你使用我的代码,它不应该给你。这很可能是因为在你的代码中,'temp2'的数据类型是'char *'而不是'const char *'。 –