0

为什么当我使用方法respondsToSelector:instancesRespondToSelector:在第 43 行时,我无法绕过 STAssertTrue?

//我的测试用例代码

- (void)testApiClass {
    //Check object
    NSString* classKey = @"Api";
    id obj = NSClassFromString(classKey);
    STAssertNotNil(obj, [NSString stringWithFormat:@"Model '%@' not found.", classKey]);
    //Check properties
    NSArray* properties =
    @[
        @"performSyncRequestWithUri::",
        @"performAsyncRequestWithUri:::",
    ];
    for (NSString* property in properties) {
        SEL propertySel = NSSelectorFromString(property);
        BOOL isRespondsToSel = [obj respondsToSelector:propertySel];
        STAssertTrue(isRespondsToSel, [NSString stringWithFormat:@"Property '%@' not found on object of class name '%@'", property, [obj class]]);
    }    
}


@interface Api : NSObject

- (NSDictionary*)performSyncRequestWithUri:(NSString *)requestUri params:(NSDictionary *)params;
- (void)performAsyncRequestWithUri:(NSString *)requestUri params:(NSDictionary *)params completionHandler:(void (^)(NSDictionary *, NSError *))completionBlock;

@end
4

2 回答 2

2

数组中的字符串常量与界面properties中的选择器不匹配Api

此外,这些选择器都没有引用属性。一个属性有两个选择器:一个 getter,like stringValue,它没有冒号,一个 setter,like setStringValue:,它有一个冒号并且(通常)以 开头set

不要将选择器嵌入字符串中,而是创建一个选择器数组:

SEL selectors[] = {
    @selector(performSyncRequestWithUri:params:),
    @selector(performAsyncRequestWithUri:params:completionHandler:),
    NULL
};

for (size_t i = 0; selectors[i]; ++i) {
    SEL selector = selectors[i];
    BOOL respondsToSelector = [obj respondsToSelector:selector];
    STAssertTrue(respondsToSelector, [NSString stringWithFormat:
        @"Object %@ doesn't respond to selector %s",
        obj, sel_getName(selector)]);
}

这里的优点是 Xcode 会为您自动完成选择器,您可以通过命令单击选择器来跳转到它们的定义。

于 2012-12-21T20:32:02.660 回答
1

这些方法被调用performAsyncRequestWithUri:params:completionHandler:performSyncRequestWithUri:params:

于 2012-12-21T19:25:22.307 回答