2012-08-16 92 views
5

假設我有此方法:發送零到CGPoint類型參數

- (void)placeView:(UIView*)theView withCenterIn:(CGPoint)centerPoint; 

所以我通過圖和點對TE視圖的中心。

但它恰巧我不需要指定中心,只是視圖。

傳遞「nil」會導致錯誤。

請建議如何跳過通過中心點。

請記住,我需要使用的方法是這樣的:

- (void)placeView:(UIView*)theView withCenterIn:(CGPoint)centerPoint{ 
    if(centerPoint == nil){//and I understand that it's a wrong comparison, as I cannot pass "nil" to CGPoint 
     //set a random center point 
    } 
    else{ 
     //set that view to the specified point 
    } 
} 

在此先感謝

回答

5

CGPoint是C struct,你不能通過nil它。您可以創建一個不拿不必要CGPoint一個單獨的方法,並擺脫你的if語句,就像這樣:

- (void)placeView:(UIView*)theView withCenterIn:(CGPoint)centerPoint{ 
    //set that view to the specified point 
} 

- (void)placeView:(UIView*)theView { 
    //set a random center point 
} 

如果你堅持不讓一個方法,你可以指定一個點作爲「特殊」(例如CGMakePoint(CGFLOAT_MAX, CGFLOAT_MAX)),將其包裝在#define中,並使用它代替nil

另一種解決辦法是換你CGPointNSValue

NSValue *v = [NSValue withPoint:CGMakePoint(12, 34)]; 
CGPoint p = [v pointValue]; 
+0

所以你建議做出2種不同的方法,對吧? – 2012-08-16 12:35:48

+0

@SavaMazăre對,這種方法在你的實現(沒有不必要的'if')和你的調用者(沒有不必要的'withCenterIn:nil')上都更清晰。 – dasblinkenlight 2012-08-16 12:36:46

+0

我明白,這是有道理的。但是如果我需要指定2個不同的點,例如:placeView:witCenterIn:orOriginAt:並且我正在檢查是否有中心,我與中心一起工作,否則我使用原點工作。我正在考慮傳遞一個CGPoint數組,並檢查索引爲0的對象是否爲零,所以我沒有得到中心 - >我將使用原點(假設實際上是一個包含2個對象的數組,其中一個爲零)。 – 2012-08-16 12:40:31

12

不能使用nil爲「沒有意義」的指標,因爲它是隻爲對象,CGPointstruct。 (正如dasblinkenlight已經說過的那樣)。

在我的幾何庫中,我定義了一個「null」CGPoint作爲「no point」佔位符,以及一個函數來測試它。由於CGPoint的成分是CGFloat s和float■找一個「無效值」表示已經 - NAN,在math.h中定義的 - 我認爲這是用最好的東西:

// Get NAN definition 
#include <math.h> 

const CGPoint WSSCGPointNull = {(CGFloat)NAN, (CGFloat)NAN}; 

BOOL WSSCGPointIsNull(CGPoint point){ 
    return isnan(point.x) && isnan(point.y); 
} 
+0

嗯..有趣.. – 2012-08-16 18:08:02

相關問題