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/