奇怪的错误NSAssert

foh*_*oho 46 objective-c nsassert

我弄清楚为什么会得到

use of undeclared identifier _cmd  did you mean rcmd
Run Code Online (Sandbox Code Playgroud)

在NSAssert的行上.

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int x = 10;

    NSAssert(x > 11, @"x should be greater than %d", x);

    [pool drain];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

hoo*_*oop 105

在每个Objective-c方法中都有两个隐藏变量id selfSEL _cmd

所以

- (void)foo:(id)bar;
Run Code Online (Sandbox Code Playgroud)

是真的

void foo(id self, SEL _cmd, id bar) { ... }
Run Code Online (Sandbox Code Playgroud)

当你打电话的时候

[someObject foo:@"hello world"]
Run Code Online (Sandbox Code Playgroud)

实际上

foo( someObject, @selector(foo), @"hello world")
Run Code Online (Sandbox Code Playgroud)

如果cmd-单击NSAssert跳转到它的定义,您将看到它是一个宏,它使用您调用它的方法的隐藏_cmd变量.这意味着如果你不在Objective-c方法中(也许你在'main'中),因此你没有_cmd参数,你就不能使用NSAssert.

相反,您可以使用替代NSCAssert.


hig*_*ted 30

NSAssert 仅用于Objective-C方法.由于main是C函数,请NSCAssert改用.