如何在 Objective-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

}

如您所见,我需要调用相同的方法但需要发送三个不同的 bool 变量!!!!

根据您的说明,如何:

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

不能 100% 确定这是否是您想要的,但您可以这样做:

[self sendBoolVariable:&b1];

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

当您将 BOOL b1 传递给方法时:

[self sendBoolVariable:b1];

"value" 的范围仅限于该方法。所以当你设置 value=YES:

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

您没有更改范围更广的 ivar 的值 "b1"。