2010-10-11 59 views
4

我發現這個代碼,here檢查UI_USER_INTERFACE_IDIOM()以確定它是iPhone還是iPad是否安全?

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]; 

安全性如何這個檢查?蘋果是否真的推薦這樣做?或者它會發生,它不會檢測iPad作爲iPad或iPhone作爲iPhone?

回答

7

它應該足夠安全,它很好 - 蘋果公司的documented

這僅僅是以下代碼的簡寫:

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

如果你試圖在任何小於的iOS 3.2(因爲它是隻介紹當時的)運行此它可以想見,失敗,但是這可能不是一個問題給你。

+0

非常感謝!這爲我解決了數萬億的問題...... – openfrog 2010-10-11 11:27:28

+1

在早期的操作系統上運行時,這實際上不會失敗。在3.2之前的操作系統中,表達式將評估爲0,這不等於1的UIUserInterfaceIdiomPad值,因此它將返回正確的結果。 – 2010-10-11 12:57:23

+2

您的陳述不正確。 'UI_USER_INTERFACE_IDIOM()'實際上定義爲'[[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)]?[[UIDevice currentDevice] userInterfaceIdiom]:UIUserInterfaceIdiomPhone)'。所以它不會在iOS 3.2以下失敗,而你的代碼將會在 – user102008 2011-03-12 00:33:24

相關問題