4
NSDate *now = [NSDate date];                                 
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];                    
[formatter setDateFormat:@"yyyy"];                     

NSString *stringFromDate = [formatter stringFromDate:now]; 
CGContextShowTextAtPoint(context, 50, 50, stringFromDate, 5);

I am not getting the exact date? also getting warning while compiling
warning: passing argument 4 of 'CGContextShowTextAtPoint' from incompatible pointer type

JBL
  • 12,588
  • 4
  • 53
  • 84
coure2011
  • 40,286
  • 83
  • 216
  • 349

2 Answers2

2

The function's prototype is:

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

but in the 4th argument you are passing a *NSString ** (and not a *const char ** as required by the function prototype).

You can convert the NSString to a C string using the cStringUsingEncoding method of the NSString, e.g.:

CGContextShowTextAtPoint(context, 50, 50, [stringFromDate cStringUsingEncoding:NSASCIIStringEncoding]);
diciu
  • 29,133
  • 4
  • 51
  • 68
  • It's OK in this context because of the date format being yyyy but in general, you should never use `[someString cStringUsingEncoding:NSASCIIStringEncoding]` without testing for a NULL return value. For instance, if the date format was set to the long date format and the code is being run on an iPhone in the French locale and the month is August (or août, as they say in France), a null pointer will be passed as the fourth parameter. The best case will be no text being displayed, the worst case will be a seg fault. – JeremyP May 28 '10 at 07:40
  • Good reason to use `UTF8String` instead. :) – Shaggy Frog May 28 '10 at 07:43
  • Good point but it looks like it's a better idea to use [NSString drawAtPoint:withFont:] ref http://stackoverflow.com/questions/1237565/iphone-cgcontextshowtextatpoint-for-japanese-characters and http://stackoverflow.com/questions/2087418/iphone-unicode-text-with-coregraphics – diciu May 28 '10 at 09:36
1

What is the value of stringFromDate? What are you expecting?

also getting warning while compiling warning: passing argument 4 of 'CGContextShowTextAtPoint' from incompatible pointer type

If you look at the docs for CGContextShowTextAtPoint, you'll see that the fourth parameter needs to be a char*, not an NSString*.

You have:

GContextShowTextAtPoint(context, 50, 50, stringFromDate, 5);

You want:

GContextShowTextAtPoint(context, 50, 50, [stringFromDate UTF8String], 5);
Shaggy Frog
  • 27,575
  • 16
  • 91
  • 128