0

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));
vanHoesel
  • 956
  • 9
  • 22

1 Answers1

4

Try this:

NSString *tmp = [NSString stringWithFormat:@"%ld", pageIndex];
const char *str = [tmp UTF8String];
size_t length = [tmp length];
  • that is basically what I did... not elegant, nasty and ugly. For completeness, I edited the question and pasted in the code. – vanHoesel Oct 23 '12 at 19:02
  • @user1765406 maybe yes. What's wrong with that? Also, why do you use the Mac Roman encoding? –  Oct 23 '12 at 19:04
  • yes, I was quite surprised at the fact that I had to use `MacRoman`, but that was what I more or less understood from the [https://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_text/dq_text.html%23](Drawing with Quartz 2D Reference). Correct me if I do it wrong and if I could draw UTF text... that would be better – vanHoesel Oct 23 '12 at 19:17
  • 1
    `%ld` should be the format specifier for an `NSInteger`. @user: The other solution is even uglier, involving `sprintf()` and `calloc()`. – jscs Oct 23 '12 at 19:17
  • odly enough, my compiler doesn't complain about %d - or is that due to iOS and OS-X differences – vanHoesel Oct 23 '12 at 19:46
  • @Th.J. Maybe yes, but IMHO that's still UB, isn't it? –  Oct 23 '12 at 20:14
  • @H2CO3: NSObjCRuntime.h (line 399): `typedef int NSInteger;` --- that might explain the warning – vanHoesel Oct 23 '12 at 21:41
  • @Th.J. Cool. In this case, use either `%d` or `%ld` and cast to the appropriate integral type in order to avoid UB arising from type promotion (which takes place since `- [NSString stringWithFormat:]` is a variadic method. –  Oct 24 '12 at 04:35