简体   繁体   English

正确的内存管理[string UTF8String]

[英]Correct Memory Management for [string UTF8String]

I'm somewhat new to objective-c and I'm not sure what the correct memory management for this code is. 我对objective-c有些新意,我不确定这段代码的正确内存管理是什么。

const unsigned char * data =(const unsigned char *) [string UTF8String];

When I call free on data I get an error. 当我对数据免费调用时,我收到错误。 Do I need to clean up after this call? 这次通话后我需要清理吗?

No. "UTF8String" does not contain the words alloc , copy , retain , or create . 不。“UTF8String”不包含单词alloccopyretaincreate Thus, you're not responsible for that memory. 因此,你不对那个记忆负责。

Note that if you want that data to stick around after string is released, you should copy it; 请注意,如果您希望在释放string后继续保留数据,则应复制它; by the contract, you're not responsible for that memory, but you are also not guaranteed that it will last beyond the scope of the object that gave it to you. 根据合同,您不对该内存负责,但您也不能保证它将超出提供给您的对象的范围。

You do not need to free it. 你不需要free它。

In Cocoa, if a method does not contain the words alloc , init , or copy , you do not own the object that is returned from said method. 在Cocoa中,如果方法不包含单词allocinitcopy ,则不拥有从所述方法返回的对象。

-UTF8String actually points to the cstring representation of the NSString object you are calling it on. -UTF8String实际上指向您调用它的NSString对象的cstring表示。 When the object's state changes, the UTF8String also changes. 当对象的状态发生变化时, UTF8String也会发生变化。

文档中所述,它会自动释放自动释放对象的方式。

technically speaking, free() is used to remove memory allocated using malloc() from the heap. 从技术上讲,free()用于从堆中删除使用malloc()分配的内存。 malloc() was not used to allocate the memory. malloc()不用于分配内存。 remember that objective-c is c with extensions. 记住,objective-c是带有扩展名的c。 the data variable will remain in memory based on the c language 'scoping' rules. 数据变量将根据c语言的“范围”规则保留在内存中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM