Objective-C如何为不同的变量运行相同的代码

时间:2014-11-28 21:58:47

标签: objective-c

我对编码很陌生,我正在寻找一种方法来运行相同的代码,但每次都需要单独的变量名称。

基本上我有多个变量需要运行相同的代码。但由于我打算让应用程序工作的方式,我不想一遍又一遍地复制和粘贴代码并更改变量名称,因为这会使我的代码不整洁,如果我想进一步改变这条线我不想每个变量编辑100行代码。

示例:

   if (Variable1 == 1{
       Object1.center.x = CGPointMake(AnotherObject1.center.x, AnotherObject1.center.y);
       Random1.hidden = NO; 
       [More code here just don't need to type this out to explain my purpose]
   }
   if (Variable2 == 1{
       Object2.center.x = CGPointMake(AnotherObject2.center.x, AnotherObject2.center.y);
       Random2.hidden = NO; 
       [More code here just don't need to type this out to explain my purpose]
   }
   if (Variable3 == 1{
       Object3.center.x = CGPointMake(AnotherObject3.center.x, AnotherObject3.center.y);
       Random3.hidden = NO; 
       [More code here just don't need to type this out to explain my purpose]
   }

我需要20个这样的if语句你说几乎都运行相同的代码但涉及不同的变量(在我的代码而不是if语句中它们可以是从IBactions到Collisions的任何东西。我只是试图使用全局示例

我基本上需要缩短它。如果我需要改变影响主要陈述的内容,我很高兴能够重复发表声明。

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用参数创建方法。

-(void)methodName:(typeOfYourVariable)variable
{
here, write the code you want to apply to each variable.
}

并通过执行此操作调用此方法

[self methodName:variable1];
[self methodName:variable2];
[self methodName:variable3];

等...

这是一个例子

- (void)viewDidLoad {
    [super viewDidLoad];
    int variable1 = 10;
    int variable2 = 15;
    int variable3 = 40;

    [self calculateSquare:variable1];
    [self calculateSquare:variable2];
    [self calculateSquare:variable3];

}

-(void)calculateSquare:(int)number
{
    NSLog(@"%i^2 = %i", number, number*number);
}

以下是控制台中的结果:

2014-11-29 00:30:49.743 Test a jeter[10134:418660] 10^2 = 100
2014-11-29 00:30:49.743 Test a jeter[10134:418660] 15^2 = 225
2014-11-29 00:30:49.743 Test a jeter[10134:418660] 40^2 = 1600

如果你想使用多个参数:

- (void)viewDidLoad {
    [super viewDidLoad];
    int variable1 = 10;
    int variable2 = 15;
    int variable3 = 40;

    [self addNumber:variable1 andNumber:variable2];
    [self addNumber:variable1 andNumber:variable3];
    [self addNumber:variable2 andNumber:variable3];

}

-(void)addNumber:(int)number1 andNumber:(int)number2
{
    NSLog(@"%i+%i = %i", number1, number2, number1 + number2);
}

结果如下:

2014-11-29 09:54:04.470 Test a jeter[10395:466552] 10+15 = 25
2014-11-29 09:54:04.471 Test a jeter[10395:466552] 10+40 = 50
2014-11-29 09:54:04.471 Test a jeter[10395:466552] 15+40 = 55

当然,您可以使用任意数量的参数,两个或更多:)您没有义务使用相同类型的参数。你可以做你想做的事^^