90

I was trying to log (print) the value of CGSize object like this:

CGSize sizeOfTab = CGSizeMake(self.frame.size.width/tabCount, 49);

NSLog(@"size of tab is %@",sizeOfTab);

Is there anything wrong in this code; my app is crashing while control comes to NSLog statement.

Thanks Prasad

Chris Markle
  • 2,076
  • 4
  • 25
  • 46
Prasad
  • 1,904
  • 4
  • 19
  • 24

6 Answers6

221

Try this

CGSize sizeOfTab = CGSizeMake(self.frame.size.width/tabCount, 49);
NSLog(@"size of tab is %@",NSStringFromCGSize(sizeOfTab));

The crash occurs because sizeOfTab is not in NSString format.

visakh7
  • 26,380
  • 8
  • 55
  • 69
59

You can call the following to print the value you are after:

NSLog(@"width = %f, height = %f", mySize.width, mySize.height);
Luke
  • 11,426
  • 43
  • 60
  • 69
11

As JoeBlow mentioned (I noticed after typing and formatting this answer), there's also the UIKit function, NSStringFromCGSize(), for pretty printing, and its inverse, CGSizeFromString(), for creating a CGSize struct from an NSString object.

Apple documents the string parameter of CGSizeFromString(string) as follows:

A string whose contents are of the form "{w, h}", where w is the width and h is the height. The w and h values can be integer or float values. An example of a valid string is @"{3.0,2.5}". The string is not localized, so items are always separated with a comma.


Example

CGSize size = CGSizeFromString(@"{320,568}");
NSLog(@"Pretty printed size: %@", NSStringFromCGSize(size));

Output

Pretty printed size: {320, 568}

Other Useful Functions (CGGeometry Reference)

  • CGRectGetHeight()
  • CGRectGetWidth()
Community
  • 1
  • 1
yurrriq
  • 641
  • 7
  • 12
6

%@ means you are trying to insert a string. CGSize is not a string, and cannot automagically be converted to one. That's why your app crashes. Instead, you need to log individual properties separately, like

NSLog(@"width is %f, height is %f.", sizeOfTab.width, sizeOfTab.height);

%f is used because the width and height properties are of the type float.

For other format conversions, see the docs: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html

Greg
  • 9,068
  • 6
  • 49
  • 91
  • Welcome to SO. +1 for a detailed answer. – Praveen S Jul 08 '11 at 09:01
  • Thanks. I had a look around and it's amazing to see how many people never bother looking at the docs before asking a question. I put the link there so we don't get another question asking how to print an _int_. – Greg Jul 08 '11 at 09:20
3

Here self.view is the view of UIView Class. You can print any frame with this log.

      NSLog(@"self.view.Frame=%@", NSStringFromCGRect(self.view.frame));
Disha
  • 608
  • 7
  • 10
3

CGSize has the memebers width and height which are of type CGFloat. You can print them using the following

NSLog(@"Width = %f, height = %f",sizeOfTab.width, sizeofTab.height);
Praveen S
  • 10,355
  • 2
  • 43
  • 69