What is the difference among NSString alloc:initWithCString versus stringWithUTF8String?

Posted by mobibob on Stack Overflow See other posts from Stack Overflow or by mobibob
Published on 2010-04-18T17:36:52Z Indexed on 2010/04/18 17:43 UTC
Read the original article Hit count: 438

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!

© Stack Overflow or respective owner

Related posts about nsstring

Related posts about allocation