I am trying to write text using a Core Graphics context. I can do it the first time, no problem, but the second time crashes my iPhone app. Here is a code snippet:
NSString *name = [MyClass getName];
const char *cname = [name UTF8String];
[self drawText:context text:cname];
MyClass and drawText are custom classes/methods but you get the idea. These three lines live in drawRect:
The first time drawRect: is executed, I see the text as expected. However, on any refresh of drawRect:, the line:
const char *cname = [name UTF8String];
causes my app to crash with the cryptic, "GDB: Program loaded." status message.
I get a similar response even when I use the getCString: method. I think I might be missing a fundamental understanding of NSString to char array conversion.
It sounds like you’re trying to call methods on an object which has been deallocated already. The
UTF8Stringmessage has the problem that you can’t hold onto the returned pointer, since it may become invalidated when the string is released — you have to copy the string if you need to hold onto it. However,getCString:maxLength:encoding:does not have that problem.Make sure you’re following properly memory management protocol. See the Memory Management Programming Guide for Cocoa, and double-check that you’re sending
retain,release, andautoreleasemessages to the proper objects at the proper times. Chances are you’re sending an extrareleaseorautoreleasewhen you shouldn’t be, or you’re forgetting toretainyour string somewhere.