guowy
guowy

Reputation: 257

iPhone SDK screen size returns different results using similar syntax

I'm new to Objective C for iPhone. I tried the following code to get the screen size, however the code below returns two different result:

CGRect screenRect = [UIScreen mainScreen].bounds;
NSLog(@"width: %d", screenRect.size.width);
NSUInteger width = [UIScreen mainScreen].bounds.size.width;
NSUInteger height = [UIScreen mainScreen].bounds.size.height;
NSLog(@"width: %d", width);

The first NSLog outputs 0, while the last one outputs 320. Why are they different? Does it have something to do with pointers? Please help.

Upvotes: 2

Views: 2337

Answers (3)

Jorge Israel Peña
Jorge Israel Peña

Reputation: 38596

The bounds property is a structure of type CGRect. I think since NSLog doesn't know how to print this, it prints a 0. The size member is a structure of type CGSize. You can print CGSize's members because they are simply CGFLoats, or floats.

EDIT: Oh, I see what the problem is now. Thought you were printing the structure itself. Misread that.

Upvotes: 0

No one in particular
No one in particular

Reputation: 2672

%d is for decimal and you're trying to print a float. Try

CGRect screenRect = [UIScreen mainScreen].bounds; 
NSLog(@"width: %f", screenRect.size.width); 
float width = [UIScreen mainScreen].bounds.size.width; 
NSLog(@"width: %f", width);

Upvotes: 2

RedBlueThing
RedBlueThing

Reputation: 42522

CGRect.size.width is a CGFloat. If you use %f in your format string, you will get 320.

Upvotes: 1

Related Questions