为什么将NSString对象传递给XCTAssertTrue的"format"参数会导致构建错误?

aki*_*don 21 macos xcode objective-c ios xctest

在尝试使用XCTest测试我的应用程序时,执行以下操作时出现构建错误:

#import <XCTest/XCTest.h>

@interface MyTests : XCTestCase

@end

@implementation MyTests

- (void)testExample
{
    NSString *str = @"foo";
    XCTAssertTrue(YES, str); // Parse issue: Expected ')'
}

@end
Run Code Online (Sandbox Code Playgroud)

但如果我这样做,我不会得到构建错误:

#import <XCTest/XCTest.h>

@interface MyTests : XCTestCase

@end

@implementation MyTests

- (void)testExample
{
    XCTAssertTrue(YES, @"foo"); // this is just fine...
}

@end
Run Code Online (Sandbox Code Playgroud)

我得到的构建错误是:

Parse issue: Expected ')' 
Run Code Online (Sandbox Code Playgroud)

它在"str"中的"s"下面放了一个箭头.

我发现我可以通过改变来解决这个问题

XCTAssertTrue(YES, str)
Run Code Online (Sandbox Code Playgroud)

XCTAssertTrue(YES, @"%@", str)
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚为什么会产生影响.有人可以解释为什么会这样吗?

Ita*_*ber 22

XCT...宏被写入接受格式字符串-字符串本身是可选的(这样写XCTAssertTrue(YES)是有效的),但必须是常量字符串.如果没有格式字符串,您就无法将对象传递到宏中,这就是为什么XCTAssertTrue(YES, @"%@", str)有效,但是,XCTAssertTrue(YES, str)或者说,或者XCTAssertTrue(NO, nil)不会.