NSString alloc:initWithCString 与 stringWithUTF8String 有什么区别?
我认为这两种方法(内存分配方面)是等效的,但是,如果我使用我认为方便的方法(在下面注释掉)并且当我切换时,我会在调试器中看到“超出范围”和“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您需要在方法返回后保留对对象的引用,那么您需要获得该对象的所有权。因此,如果您的变量
GUID
是实例变量或某种全局变量,您将需要获得该对象的所有权。如果您使用 alloc/init 方法,则您拥有自使用alloc
以来返回的对象的所有权。您可以轻松使用stringWithUTF8String:
方法,但您需要通过发送retain
消息来显式获取所有权。因此,假设GUID
是某种非方法范围的变量:(这里可以使用
copy
或retain
来获取所有权,但是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 usedalloc
. You could just as easily use thestringWithUTF8String:
method, but you will need to take ownership explicitly by sending aretain
message. So, assumingGUID
is some kind of non-method-scoped variable:(either
copy
orretain
can be used here to take ownership, butcopy
is more common when dealing with strings).Also, your code may be a little easier to read if you did something like: