NSString alloc:initWithCString 与 stringWithUTF8String 有什么区别?

发布于 2024-08-29 04:19:17 字数 476 浏览 6 评论 0原文

我认为这两种方法(内存分配方面)是等效的,但是,如果我使用我认为方便的方法(在下面注释掉)并且当我切换时,我会在调试器中看到“超出范围”和“NSCFString”使用更明确的方法我的代码不再崩溃!请注意,我从 sqlite3 查询中获取了存储在容器中的字符串。

p = (char*) sqlite3_column_text (queryStmt, 1);
// GUID = (NSString*) [NSString stringWithUTF8String: (p!=NULL) ? p : ""];
GUID = [[NSString alloc] initWithCString:(p!=NULL) ? p : "" encoding:NSUTF8StringEncoding];

另请注意,如果我查看调试器中的值并使用 NSLog 打印它们,它们看起来是正确的,但是,我认为没有分配新内存并复制值。相反,内存指针被存储 - 超出范围 - 稍后引用 - 崩溃!

I thought these two methods were (memory allocation-wise) equivalent, however, I was seeing "out of scope" and "NSCFString" in the debugger if I used what I thought was the convenient method (commented out below) and when I switched to the more explicit method my code stopped crashing! Notice that I am getting the string that is being stored in my container from sqlite3 query.

p = (char*) sqlite3_column_text (queryStmt, 1);
// GUID = (NSString*) [NSString stringWithUTF8String: (p!=NULL) ? p : ""];
GUID = [[NSString alloc] initWithCString:(p!=NULL) ? p : "" encoding:NSUTF8StringEncoding];

Also note, that if I looked at the values in the debugger and printed them with NSLog they looked correct, however, I don't think new memory was allocated and the value copied. Instead the memory pointer was stored - went out of scope - referenced later - crash!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

澜川若宁 2024-09-05 04:19:18

如果您需要在方法返回后保留对对象的引用,那么您需要获得该对象的所有权。因此,如果您的变量 GUID 是实例变量或某种全局变量,您将需要获得该对象的所有权。如果您使用 alloc/init 方法,则您拥有自使用 alloc 以来返回的对象的所有权。您可以轻松使用 stringWithUTF8String: 方法,但您需要通过发送 retain 消息来显式获取所有权。因此,假设 GUID 是某种非方法范围的变量:(

GUID = [[NSString stringWithUTF8String:"Some UTF-8 string"] copy];

这里可以使用 copyretain 来获取所有权,但是copy 在处理字符串时更常见)。

另外,如果您执行以下操作,您的代码可能会更容易阅读:

GUID = p ? [[NSString stringWithUTF8String:p] copy] : @"";

If you need to keep a reference to an object around after a method returns, then you need to take ownership of the object. So, if your variable GUID is an instance variable or some kind of global, you will need to take ownership of the object. If you use the alloc/init method, you have ownership of the object returned since you used alloc. You could just as easily use the stringWithUTF8String: method, but you will need to take ownership explicitly by sending a retain message. So, assuming GUID is some kind of non-method-scoped variable:

GUID = [[NSString stringWithUTF8String:"Some UTF-8 string"] copy];

(either copy or retain can be used here to take ownership, but copy is more common when dealing with strings).

Also, your code may be a little easier to read if you did something like:

GUID = p ? [[NSString stringWithUTF8String:p] copy] : @"";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文