内存管理:的NSString的stringWithCString:编码: [英] Memory Management: NSString's stringWithCString:encoding:

查看:675
本文介绍了内存管理:的NSString的stringWithCString:编码:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假如我得到一些功能的C字符串:

Suppose I'm getting a C string from some function:

的char * MyString的= SomeCFunction(...);

和我自己的这个字符串(我负责释放它,当我做了)。

And I own this string (I'm responsible for freeing it when I'm done).

如果,在Objective-C,我创建一个的NSString * 使用:

If, in Objective-C, I create an NSString * using:

NSString * mynsstring = [NSString stringWithCString:mystring 
                                           encoding:NSUTF8StringEncoding];

我仍然负责释放原始的C字符串?

我假设的答案是肯定的,但我不能找到文档中的一个确定的答案 - 而相反的方法的功能( cStringUsingEncoding ),而无意义的,确实给我停下来,因为它处理的CString的释放你。

I'm assuming the answer is yes, but I can't find a definitive answer in the documentation - and the functionality of the opposite method (cStringUsingEncoding), while sensical, does give me pause, because it handles the cString freeing for you.

如果答案是肯定的,那就是我还负责确保我不释放C字符串之前,我用做了的NSString * ,或不该函数复制字符串给我吗?我问这个,因为 stringWithCString 的文件说的:

If the answer is yes, then am I also responsible for making sure I don't free the c string before I'm done using the NSString *, or does the function copy the string for me? I ask this because the documentation for stringWithCString says it:

返回包含在定的C数组字节的字符串,除preTED
  根据给定的编码

Returns a string containing the bytes in a given C array, interpreted according to a given encoding.

这仍然让我想知道如果它实际复制的字节数,或者他们只是指向内部(我基本上只是在做类型转换)。

Which still leaves me wondering if it actually copied the bytes, or is just pointing at them internally (and I'm basically just doing a cast).

推荐答案

它确实复制字节。

如果您不希望字节要复制这样做,你可以使用 - (ID)initWithBytesNoCopy:(无效*)字节长度:(NSUInteger)长度编码:(NSStringEncoding)编码freeWhenDone :(布尔)标记代替。

If you don't want the bytes to be copied, you may use - (id)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length encoding:(NSStringEncoding)encoding freeWhenDone:(BOOL)flag instead.

如果您使用 - (ID)initWithBytes:(常量无效*)字节长度:(NSUInteger)长度编码:(NSStringEncoding)编码,或任何商品的方法如 stringWithCString:编码:本身调用这个低层次的方法,该字节被复制

If you use - (id)initWithBytes:(const void *)bytes length:(NSUInteger)length encoding:(NSStringEncoding)encoding, or any commodity method like stringWithCString:encoding: that itself calls this low-level method, the bytes are copied.

这篇关于内存管理:的NSString的stringWithCString:编码:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆