[英]NSString and Objective-C Memory Management ARC
I'm a little confused when coding an Objective-C project. 在编写Objective-C项目时,我有些困惑。 The ARC is on.
ARC已打开。 Here is a sample code:
这是一个示例代码:
NSString *foo = [[NSString alloc] initWithUTF8String:"This is a C string."];
// Use foo here...
foo = @"This is an ObjC string."
Here are my questions: 这是我的问题:
Do I need to explicitly terminate C string with '\\0' in initWithUTF8String:
method, or it is okay to omit NULL terminator? 我是否需要在
initWithUTF8String:
方法中以'\\ 0'显式终止C字符串,还是可以省略NULL终止符?
Is there any memory leakage when I reuse foo
as a pointer and assign new Objective-C string to it? 当我将
foo
用作指针并为其分配新的Objective-C字符串时,是否存在任何内存泄漏? Why? 为什么?
If I change NSString
to other class, like NSObject
or my own class, is there any difference for question 2? 如果我将
NSString
更改为其他类,例如NSObject
或自己的类,问题2有什么区别吗? (Initialize an object and then reassign other value directly to it.) (初始化一个对象,然后直接将其他值重新分配给它。)
Thank you! 谢谢!
Do string literals that end with a null-terminator contain an extra null-terminator? 以null终止符结尾的字符串文字是否包含额外的null终止符?
No memory leakage. 没有内存泄漏。 The ARC-configured compiler will generate code to release the first string that was being referenced before assigning the new string.
配置了ARC的编译器将生成代码,以在分配新字符串之前释放被引用的第一个字符串。
No change. 没变。 You may get a compile-time warning if the types aren't compatible.
如果类型不兼容,则可能会收到编译时警告。
For the first question, what Apple's official documentation tells me is: 对于第一个问题,Apple的官方文档告诉我的是:
Returns a string created by copying the data from a given C array of UTF8-encoded bytes.
返回一个字符串,该字符串是通过从给定的UTF8编码字节的C数组复制数据而创建的。
- (id)stringWithUTF8String:(const char *)bytes Parameters bytes A NULL-terminated C array of bytes in UTF8 encoding.
(id)stringWithUTF8String:(const char *)bytes参数bytes一个以NULL终止的C字节数组,采用UTF8编码。
But since string literal is NULL terminated by default (as @TomSwift points out), it's okay to omit it. 但是由于字符串文字默认情况下为NULL终止(如@TomSwift指出的那样),可以省略它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.