如何在Objective C中创建Dynamic方法

时间:2014-12-18 03:26:49

标签: objective-c

我必须创建返回数字的方法,这里是我的代码,无论我尝试但我想为我的代码做常用的方法,在我的代码中我有相同的逻辑但是数字,number1的值是不同的, 我该如何创建方法?或者以哪种方式为我的代码做常用的方法我不必为传送的数字编写相同的逻辑

COMMON CODE ONLY number,number1的值变化     #PART 1:

number = [First_color objectForKey:[json objectForKey:@"startColor"]];   // Different from PART2 
number1 = [Last_color objectForKey:[json objectForKey:@"endColor"]];     // Different from PART2 

 //Same code For Both Part
 if(number)
    {
         a = [number integerValue];
         if(a == 14) {
            b = 11; a = 10;
         }
         else
            [Search addObject:[Data objectAtIndex:[number integerValue]]];
    }

    if(number1)
    {
        b = [number1 integerValue];
        if(a == 10) {
            b = 11; a = 10;
        }
        else
            [Search addObject:[Data objectAtIndex:[number1 integerValue]-1]];
    }

#PART 2:

     number = [First_color objectForKey:[objSearch.search firstObject]];  //Different from PART1
     number1 = [Last_color objectForKey:[objSearch.search lastObject]];   // Different from PART2 

   // Same code for both Part
    if(number)
    {
         a = [number integerValue];
         if(a == 14) {
            b = 11; a = 10;
         }
         else
            [Search addObject:[Data objectAtIndex:[number integerValue]]];
    }

    if(number1)
    {
        b = [number1 integerValue];
        if(a == 10) {
            b = 11; a = 10;
        }
        else
            [Search addObject:[Data objectAtIndex:[number1 integerValue]-1]];
    }

1 个答案:

答案 0 :(得分:3)

为什么你不能简单地将你的数字作为该函数的参数传递?这样你就可以用数字作为参数制作一个通用的方法。

-(void)someMethodNameWithNumber:(NSNumber*)number number2:(NSNumber*)number1
{
    if(number)
    {
         a = [number integerValue];
         if(a == 14) {
            b = 11; a = 10;
         }
         else
            [Search addObject:[Data objectAtIndex:[number integerValue]]];
    }

    if(number1)
    {
        b = [number1 integerValue];
        if(a == 10) {
            b = 11; a = 10;
        }
        else
            [Search addObject:[Data objectAtIndex:[number1 integerValue]-1]];
    }
}