NSInteger to const char *

2.2k Views Asked by At

I am handed a (NSInteger) pageIndex and need to print that on a page with

void CGContextShowTextAtPoint ( CGContextRef c, CGFloat x, CGFloat y, const char *string, size_t length );

how do I get the const char *string and not to forget the length of that string

I tend to end up with nasty tricks to convert the integer to a string first and then do cStringUsingEncoding:NSMacOSRomanStringEncoding but that can't be the most elegant way

for completeness, here is the code

const char *pageIndexString = [[NSString stringWithFormat:@"%d", pageIndex] cStringUsingEncoding:NSMacOSRomanStringEncoding];
CGContextShowTextAtPoint(CGContextRef, CGFloat x, CGFloat y, pageIndexString, strlen(pageIndexString));
1

There are 1 best solutions below

8
On

Try this:

NSString *tmp = [NSString stringWithFormat:@"%ld", pageIndex];
const char *str = [tmp UTF8String];
size_t length = [tmp length];