簡體   English   中英

如何在BOOL-C中將BOOL變量作為參數傳遞?

[英]How to pass BOOL variable as parameter in Objective-C?

這可能是一個愚蠢的問題,但是在我的應用程序中,需要將bool變量傳遞給方法。

假設我有10個BOOL變量聲明為b1,b2.....b10

我可以通過以下代碼簡單地發送BOOL值作為參數:

[self sendBoolValue:YES];      

- (void)sendBoolValue:(BOOL)value 
{
    b1 = value;
    // now b1 will be YES.
}

現在,我需要執行以下操作:

[self sendBoolVariable:b1];  // I tried sending &b1, but it didnt work out. 

- (void)sendBoolVariable:(BOOL)value
{
    value = YES; // trying to set b1 to YES.
    // b1 is still NO.
}

我無法發送BOOL變量。 這有可能嗎?

為什么我要這樣做?:

我有一個UIView在3x3的網格布局中有9個子視圖(我稱它們為圖塊)。

我有兩個BOOLstartTileendTile 我需要基於觸摸設置這些值!

我正在使用touches-Began/Moved/Ended檢測這些視圖上的觸摸

觸摸開始時,我需要計算觸摸是在tile1還是tile2中.....

所以實際的代碼:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// calculate touch point and based on it set the bool value
    [self sendBoolVariable:startTile];
  //startTile is selected, so change its color
  // lock other tiles    

}


-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

  //if touches came to tile 2 region
  [self sendBoolVariable:b2];   //b2 is BOOL variable for tile2 



}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self sendBoolVariable:endTile]; 

    //end tile is selcted too
     //at this point both start tile and tile are selected
     //now do the animation for the start tile and end tile
     //other tiles are still in locked state

}

如您所見,我需要調用相同的方法,但需要發送三個不同的布爾變量!

不能100%確定這是否是您想要的,但是您可以這樣做:

[self sendBoolVariable:&b1];

- (void)sendBoolVariable:(BOOL *)value {
    *value = YES; //b1 is now YES        
}

按照您的說明,如何:

BOOL a = YES;
a = [self modifyBoolValueBasedOnItself:a]; // the method takes the BOOL as a parameter and returns the modified value 

BOOL只是一個已簽名的字符。 如果要更改屬性的值,請嘗試self.variable = YES或_variable = YES

還因以下原因而對巴里·沃克Barry Wark)表示敬意

根據objc.h中的定義:

typedef signed char     BOOL; 
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" 
// even if -funsigned-char is used.
#define OBJC_BOOL_DEFINED
#define YES             (BOOL)1
#define NO              (BOOL)0

將BOOL b1傳遞給方法時:

[self sendBoolVariable:b1];

“值”的范圍僅限於該方法。 因此,當您設置value = YES時:

-(void)sendBoolVariable:(BOOL) value{
         value=YES;

您沒有更改更廣泛范圍的變量“ b1”的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM