NSString in C-style char crash on second drawRect call
I am trying to write text using the Core Graphics context. I can do it the first time, no problem, but the second time my iPhone app crashes. Here's a snippet of code:
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 indrawRect:
On first execution, drawRect:
I see the text as expected. However, on any update to drawRect :, the line:
const char *cname = [name UTF8String];
crashes my app with cryptic status message "GDB: Program loaded."
.
I am getting a similar response even when I use the method getCString:
. I think I may be missing a fundamental understanding of converting an NSString array to char.
a source to share
It looks like you are trying to call methods on an object that has already been deallocated. The post UTF8String
has a problem that you cannot hold a valid pointer as it might become invalid when the line is emitted - - you need to copy the line if you need to hold it. However getCString:maxLength:encoding:
does not have this problem.
Make sure you are following the memory management protocol correctly. See. Programming Guide for Cocoa memory and double check that you send retain
, release
and autorelease
posts the corresponding objects in the proper time. Chances are you are posting extra release
or autorelease
when you shouldn't be, or you are forgetting retain
your line somewhere .
a source to share
The most likely reason is that you are keeping a reference to the previously returned char * and you are casting it on the second call. According to the spec, the pointer is not valid for storage: The returned C string is automatically freed as soon as the returned object is returned; you must copy the C line if you need to keep it outside of the autorun context in which the C line is created.
a source to share