gpt4 book ai didi

ios - Q : how to refactor repeating if block code with properties as much as possible?

转载 作者:行者123 更新时间:2023-11-29 13:51:46 24 4
gpt4 key购买 nike

我想尽可能将以下具有属性访问权限的重复代码压缩到 for 循环或使用函数中:

    if (sender == self.section1SegmentedControl) {
switch (sender.selectedSegmentIndex) {
case 0: //YES
self.DSProtokoll.section1YesNo = TRUE;
break;
case 1: //NO
self.DSProtokoll.section1YesNo = FALSE;
break;
}
}
if (sender == self.section2SegmentedControl) {
switch (sender.selectedSegmentIndex) {
case 0: //YES
self.DSProtokoll.section2YesNo = TRUE;
break;
case 1: //NO
self.DSProtokoll.section2YesNo = FALSE;
break;
}
}
if (sender == self.section3SegmentedControl) {
switch (sender.selectedSegmentIndex) {
case 0: //YES
self.DSProtokoll.section3YesNo = TRUE;
break;
case 1: //NO
self.DSProtokoll.section3YesNo = FALSE;
break;
}
}

我试着把它放在一个函数中:

- (void)processYesNoIfMatch:(UISegmentedControl *)sender source:(UISegmentedControl *) a dest:(BOOL *) b {
if (sender == a) {
switch (sender.selectedSegmentIndex) {
case 0: //YES
*b = TRUE;
break;
case 1: //NO
*b = FALSE;
break;
}
}
}

但我无法使用该函数并使用不同的参数多次调用它:

[self processYesNoIfMatch:sender source:self.section1SegmentedControl dest:&self.DSProtokoll.section1YesNo];
[self processYesNoIfMatch:sender source:self.section2SegmentedControl dest:&self.DSProtokoll.section2YesNo];

因为不允许使用指向属性的指针

Address of property expression requested

在objective-c中如何用函数或for循环尽可能地简化这种重复的原始代码?

最佳答案

Objective-C 方法调用使用动态绑定(bind),如果您乐于用一些编译时检查来换取可能的运行时错误,您可以大大缩短代码。将以下内容视为伪代码(因为它已直接输入到答案中并且只是代码片段):

for(int controlNumber = 1; controlNumber <= MAX_CONTROL_NUMBER; controlNumber++)
{
// construct the property name as a *string*
NSString *controlProperty = [NSString stringWithFormat:@"section%dSegmentedControl", controlNumber);
// get the property value - if the property does not exist this is a runtime error
NSSegmentedControl *controlN = [self valueForKey:controlProperty];
if (sender == controlN)
{
// construct the property path as a *string*
NSString *yesNoProperty = [NSString stringWithFormat:@"DSProtokoll.section%dYesNo", controlNumber;
// set the property value, must pass the BOOL as an NSNumber object
[self setValue:@(sender.selectedSegmentIndex == 0) forKeyPath:yesNoProperty];
// all done, exit loop
break;
}
}

还有其他方法可以解决这个问题。您的特定尝试失败只是因为您试图获取一个属性的地址,就好像它是一个变量;属性是一对函数,一个getter和setter,你可以获取这些函数的地址,并将它们传递给其他函数来调用。然而,您可能会发现传递一个设置属性的 block 比传递一个指向属性 setter 的函数指针更容易。通过这样的更改,您的 processYesNoIfMatch 方法将起作用。

HTH

关于ios - Q : how to refactor repeating if block code with properties as much as possible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59342786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com