【问题标题】:How to map xml (objects) to methods in Objective-C?如何将 xml(对象)映射到 Objective-C 中的方法?
【发布时间】:2012-04-11 13:41:19
【问题描述】:

我有一个包含结构的 xml 文件。在这个结构中,我有 Actions 节点。所以在 Actions 节点下,有多个“Action”节点,每个节点都有 Value 和 Name 属性。

例如

<?xml version="1.0" encoding="ISO-8859-1"?>

<Testcases SuiteName="CalculatorActions">

    <Testcase id="101" Name="testAddFunction">
        <Setup/>
        <TearDown/>
        <Test>
            <Action Name="Enter first operand" Type="input" Value="5"/>
            <Action Name="Enter second operand" Type="input" Value="3"/>
            <Action Name="Select operator" Type="input" Value="+"/>
            <Action Name="Click Calculator" Type="operation"/>
        </Test>
        <Validations>
            <Action Name="Validate result" Type="output" Value="8"/>
        </Validations>
    </Testcase>

</Testcases>

我想做的是;我想将这些操作映射到我在 Objective-C 中实现的方法。

假设我有一个类叫做; “CalculatorActions”并在里面定义了5个方法。我想将我在 xml(文本格式)中的操作映射到我在 CalculatorActions 中创建的方法。

例如

@interface CalculatorActions : NSObject

// Property
@property (strong, nonatomic) NSString* actionScript;

// Actions
- (void)enterFirstOperand:(double)operand;

- (void)enterSecondOperand:(double)operand;

- (void)selectOperator:(NSString*)operator;

- (void)clickCalculate;

// Validations

-(void)validateResult:(NSString*)exptectedResult;

@end

所以当我读取 xml 文件时,我想将 xml 文件中的操作映射到类中的相应方法。

我认为我正在寻找类似的东西;

@interface CalculatorActions

[Action("addOperand", "Enter first operand")]
- (void) addOperand:(double)operand1 ToOther:(double)operand2;

最好的方法是什么?

【问题讨论】:

  • 您使用什么规则将操作名称转换为方法名称?因为在您展示的示例中它们并不相同。

标签: objective-c ios xml cocoa-touch mapping


【解决方案1】:

您可以创建一个NSInvocation 实例,设置选择器、参数,并可选择捕获返回值。您可以使用字符串创建这些。

例如

SEL mySelector = NSSelectorFromString(@"testAddFunction");
Class MyClass = NSClassFromString(@"CalculatorActions");
NSString *myArgument = @"5";

NSInvocation *myInvocation = [NSInvocation invocationWithMethodSignature:[MyClass instanceMethodSignatureForSelector:mySelector]];
[invocation setTarget:myClass];
[invocation setSelector:mySelector];
[invocation setArgument:&myArgument atIndex:2];
[invocation invoke];

注意 - setArgument: 选择器采用指针地址,参数的索引从 2 开始。

【讨论】:

  • +1 用于提及 NSInvocation 允许对您正在调用的内容进行参数。 performSelector 也可以工作,但仅限于一个“withObject”
【解决方案2】:

通过一些基本的字符串操作,您可以将"Enter first operand" 转换为NSString @"enterFirstOperand"

componentsSeparatedByString:capitalizedString-[NSArray componentsJoinedByString:]

您可以使用NSSelectorFromString() 创建一个SEL(选择器)。您可以使用 [self performSelector:aSelecor][self performSelector:aSelector withObject:object afterDelay:0]variants 执行此操作。

要检查某个选择器是否可以工作,请使用responseToSelector:

对于解析本身,你会发现很多帖子都在处理它。

【讨论】:

    猜你喜欢
    • 2010-09-10
    • 2011-08-09
    • 2021-04-13
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多