objective-c - 为什么 cStringUsingEncoding : returns const char * instead of char *?

标签 objective-c c pointers constants

cStringUsingEncoding:返回一个“const char *”,尽管它返回一个动态分配的 C 字符串(来自它的文档)。那么,这里 const 的目的是什么?我们可以通过强制转换为 char * 来简单地修改返回的 C 字符串。

cStringUsingEncoding:

The returned C string is guaranteed to be valid only until either the receiver is freed, or until the current autorelease pool is emptied, whichever occurs first.

我认为库遵循指向常量指针的常见做法;预计不会被修改或发布。

From Objective-C runtime;

const char * object_getClassName(id obj) -- Nothing specified about the returned string.

char * method_copyArgumentType(Method method, unsigned int index) -- You must free the string with free(). (May be it's advising because of it's returning a copy.)

最佳答案

常见的模式是您不应该修改不属于您的缓冲区。 const 记录并(某种程度上)强制执行此操作。

至于cStringUsingEncoding:,文档说返回的缓冲区仅在您从中接收它的 NSString 期间有效,或者在当前自动释放池的持续时间内有效。这意味着您拥有返回的缓冲区,因为您不需要释放它。

运行时中的最后两个示例遵循相同的约定:

  • const char * object_getClassName(id obj)

    不通知您应该释放缓冲区,并且名称中不包含您拥有该缓冲区的任何指示。因此,您不 free() 它,也不修改它。

  • char * method_copyArgumentType(Method method, unsigned int index)

    文档明确告诉您应该释放缓冲区,并且函数名称包含说明性的 copy,这也暗示您拥有缓冲区。因此,您可以随意修改它,并且必须 free() 它。

关于objective-c - 为什么 cStringUsingEncoding : returns const char * instead of char *?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12202374/

相关文章:

objective-c - Google+ iOS API 包装器

在虚拟机上运行时 cURL MIME 数据损坏

c# - 如何制作像 Popcorn Time 这样的 GUI?

objective-c - 如何从 Swift 中的 void UnsafePointer 中提取数据?

c++ - 为什么 C++ 库和框架从不使用智能指针?

c - 如何不使用方括号而是使用指针在数组中存储一组值

objective-c - 如何识别xcode中未使用的方法

ios - NS字符串 : leak when assigning value to a property

ios - 多个 Storyboard未加载本地化

c - 创建自己的幂函数的程序运行时错误