4

I've found this code, here:

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        str = [NSString stringWithString:@"Running as an iPad application"];
    } else {
        str = [NSString stringWithString:
                  @"Running as an iPhone/iPod touch application"];
    }

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Platform"
                                                    message:str
                                                   delegate:nil
                                          cancelButtonTitle:@"OK" 
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];   

How safe is this check? Does Apple actually recommend doing this? Or can it happen that it won't detect an iPad as iPad, or iPhone as iPhone?

openfrog
  • 40,201
  • 65
  • 225
  • 373

1 Answers1

7

It should be safe enough, it's well-documented by Apple.

That is just shorthand for the following code:

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
// etc

It could conceivably fail if you tried to run this on anything less than iOS 3.2 (as it was only introduced then), but this might not be an issue for you.

Aidan Steele
  • 10,999
  • 6
  • 38
  • 59
  • 1
    This actually doesn't fail when run on earlier OSs. On a pre-3.2 OS, the expression will evaluate to 0, which is not equal to the UIUserInterfaceIdiomPad value of 1, so it will return the correct result. – Brad Larson Oct 11 '10 at 12:57
  • 2
    Your statement is not correct. `UI_USER_INTERFACE_IDIOM()` is actually defined as `([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? [[UIDevice currentDevice] userInterfaceIdiom] : UIUserInterfaceIdiomPhone)`. So it will not fail on iOS < 3.2, while your code will – user102008 Mar 12 '11 at 00:33
  • @Brad Larson: The code presented there *will* fail on a pre-3.2 OS. No, the expression does not evaluate to 0, it will throw an exception because the `userInterfaceIdiom` selector is not recognized by the non-null `UIDevice` object. – user102008 Mar 12 '11 at 00:35
  • @user102008 - I think something may have been removed from the comments here, because my comment was directed toward the use of the `UI_USER_INTERFACE_IDIOM()` macro, not the exact code in the answer. You're right, the code shown in the answer above will throw an exception on older OS versions, but the macro won't. – Brad Larson Mar 12 '11 at 14:41