NSLog with CGPoint data

42,914

Solution 1

Actually, the real easiest way to log a CGPoint is:

NSLog(@"%@", NSStringFromCGPoint(point));

The desktop Cocoa equivalent is NSStringFromPoint().

Solution 2

point.x is a floating point number, so you should use:

NSLog(@"x: %f", point.x);

Solution 3

The simplest way to log a CGPoint value is to use the NSValue class, since it will give you all the relevant values formatted nicely for the console. It's done like so:

NSLog(@"myPoint = %@", [NSValue valueWithCGPoint:myPoint]);

You can also use the +valueWithCGRect and +valueWithCGSize methods of NSValue when you're trying to log, say, the frame (CGRect) or size (CGSize) properties of a UIView.

Solution 4

NSLog(@"point x,y: %f,%f", point.x, point.y);

Share:
42,914
Spanky
Author by

Spanky

Updated on May 23, 2020

Comments

  • Spanky
    Spanky almost 4 years

    I have a CGPoint called point that is being assigned a touch:

    UITouch *touch = [touches anyObject];
    
    CGPoint point = [touch locationInView:self];
    

    I want to get the x coordinate value into my console log:

    NSLog(@"x: %s", point.x);
    

    When I use this, log output for this is:

    x: (null)

    I have verified that point is not null when this is called using the debugger and variable watch.

    Any help appreciated,

    Thanks // :)

  • Spanky
    Spanky over 14 years
    This is even better. The first answer is the easiest and lightest weight way. But this gets me both x and y from the CGPoint in one set. Nice :) Great tool :)
  • Jens Ayton
    Jens Ayton over 13 years
    Since StackOverflow saw fit to reintroduce this question in my RSS feed, I may as well pimp my general solution: jens.ayton.se/blag/almost-elegant-cave-man-debugging which allows you to go JA_DUMP(point); and get “point = { 43, 96 }” logged without having to worry about format codes.
  • Dan Rosenstark
    Dan Rosenstark over 13 years
    How do I use your lib since it compiles on I386 but not on ARM? I mean, how can I work on iOS projects using it?
  • Jens Ayton
    Jens Ayton over 13 years
    First, you’d need to build the FindAlignment.c file as an iOS app and run it on a device (not simulator). Then, copy the result into a new #elif block before the #else at line 172 in JAValueToString.m. If this doesn’t work, additional debugging will be required. I can’t do it since I’m not in the iOS programme.
  • djskinner
    djskinner over 11 years
    Also worth noting that NSStringFromCGRect() exists too.
  • johndpope
    johndpope about 11 years
    you can this helper to keep code clean #define CGLog(a) NSLog(@"%@", NSStringFromCGPoint(a))