Zebra Propulsion Lab
Zebra Propulsion Lab

Reputation: 1746

Work around of "No known instance method for selector" error for id type

My iPhone app has a login view controller to pop up whenever it is necessary to login. After the user loged in, I have this:

    if ([self.presentingViewController respondsToSelector:@selector(userDidLogin)]) {
        [((id)self.presentingViewController) userDidLogin];
    } else {
        [self.presentingViewController dismissModalViewControllerAnimated:YES];            
    }

However, the compiler kept complaining about "No known instance method for selector userDidLogin". Then I added an instance method named userDidLogin for the login view controller, which was of course not self.presentingViewController, then the build succeeded.

This workaround feels unreasonable to me. Is it a bug in Xcode or intended behavior? Is it is the latter, what is the rationale?

Upvotes: 3

Views: 1839

Answers (1)

rob mayoff
rob mayoff

Reputation: 385670

The compiler needs to know the return type of the userDidLogin selector so that it can generate correct code:

  • If the message returns a struct, the compiler may need to generate a call to objc_msgSend_stret. (Source: Greg Parker's blog.)
  • If the message returns a floating-point number, the compiler needs (on some platforms) to generate a call to objc_msgSend_fpret. (Source: Greg Parker's blog.)
  • Otherwise, the compiler needs to generate a call to objc_msgSend.

The userDidLogin selector has no arguments, but if the selector did have arguments, the compiler would also need to know the declared argument types so it could pass the arguments correctly.

Additionally, if you're using ARC, the compiler needs to know the return type and ownership annotations of the selector so that it can generate a release of the return value if appropriate.

The usual way to handle this is just to #import the header file of the class that declares the userDidLogin message. As long as the compiler has seen the selector declared somewhere, it won't complain about sending it to an id.

Upvotes: 5

Related Questions