繁体   English   中英

如何使用Objective-C动态调整方法名称和调用

[英]How to dynamically adjust method names and calls with Objective-C

我试图压缩我的代码的方法,并想知道我将如何实现以下目标:

我有一堆变量只有它们的数量不同,例如:

int intVariable1
int intVariable2
UILabel Label1
UILabel Label2
BOOL bool1
BOOL bool2

等等

所以我想调用一个方法并传入一个int。 该int将确定哪些int,UILablels和BOOL可以使用。 因此,如果在方法中传递1将对这些变量起作用,如下所示:

- (void) DyanamicMethod: (int) inputNumber {
     //something that uses the inputNumber to act on the 1 variables

     intVariable1 = someValue;
     [Label1 setText:someText];
     bool1 = YES;
}

显然,如果传入2,我希望变量属于2类型。 我假设你会以某种方式创建一个字符串,但我不确定如何调整它以使用它成为变量名称。 任何见解将不胜感激。 感谢您的时间。

将变量声明为数组:

int intVariable[2];
UILabel *Label[2];
BOOL bools[2];

那么方法看起来像这样:

intVariable[inputNumber] = someValue;
[Label[inputNumber] setText:@"someText"];
bools[inputNumber] = YES;

请记住,数组索引是从零开始的,所以在上面的数组中,变量“1”在索引0处,变量“2”在索引1处。您的方法也可以只取inputNumber并从中减去一个以获得数组索引。

您可以使用键值编码。

- (void) DyanamicMethod: (int) inputNumber {
     //something that uses the inputNumber to act on the 1 variables

     NSString* key = [NSString stingWithFormat:@"Label%i", number];
     UILabel* label = [self valueForKey:key];
     label.text = newString;
}

如果您需要类似的东西,可以保留所有标签的NSArray ...就像在类接口部分一样:

NSArray* labels ;

在init :(或loadView)

labels = [[NSArray alloc] initWithObjects:Label1, Label2,etc] ;

在dealloc中:

[labels release] ;

在DyanamicMethod中:(int)inputNumber

UILabel* label = [labels objectAtIndex:inputNumber] ;

对每种类型重复...或者创建一个包含标签,int和bool的新类,并使数组具有该类型。

另一种方式可能是:
为每个成员变量创建属性。
然后在你的功能:

UILabel label1 = [self performSelector:sel_getUid([[NSString stringWithFormat:@"label%d", inputNumber] UTF8String])] ;

我认为使用某种数组对于这种情况更好,但它可以这样做。 有关performSelector的信息 ,请参阅NSObject文档

您可以使用属性执行此操作(嗯,您不需要属性,但它们会使其更简单),但您必须切换到对象:

@property (nonatomic, readwrite, retain) NSNumber *variable1, *variable2;
@property (nonatomic, readwrite, retain) NSNumber *bool1, *bool2;
@property (nonatomic, readwrite, retain) UILabel *label1, *label2;

- (void) DyanamicMethod: (int) inputNumber { 
    [[self valueForKey: [NSString stringWithFormat: @"label%d", inputNumber] setText: someText];
    [self setValue: [NSNumber numberWithInt: inputNumber] 
            forKey: [NSString stringWithFormat: @"variable%d", inputNumber]];
    [self setValue: [NSNumber numberWithBool: YES] 
            forKey: [NSString stringWithFormat: @"bool%d", inputNumber]];
}

对于简单的switch语句,您是否有太多变量?

switch(inputNumber) {
  case 1:
    intVariable1 = someValue;
    [Label1 setText:someText];
    bool1 = YES;
    break;
  case 2:
    intVariable2 = someValue;
    [Label2 setText:someText];
    bool2 = YES;
    break;
// etc
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM