Tobias
Tobias

Reputation: 6507

How to fix 'may not respond to' for selector introduced in newer SDK?

I have an application which builds against the 10.5 SDK. I still want it to behave correctly when running on 10.7 systems. The code snippet

if ([window respondsToSelector:@selector(setRestorable:)])
{
  [window setRestorable:NO];
}

however, triggers the compiler warning

'NSWindow' may not respond to '-setRestorable:'

because the setRestorable selector was introduced in the 10.7 SDK. What would be the proper way to fix this?

Upvotes: 1

Views: 128

Answers (3)

user102008
user102008

Reputation: 31313

Simply cast it to id:

if ([window respondsToSelector:@selector(setRestorable:)])
{
  [(id)window setRestorable:NO];
}

Upvotes: 0

Tobias
Tobias

Reputation: 6507

One possibility I found was this:

if ([window respondsToSelector:@selector(setRestorable:)])
{
  IMP setRestorableFunc =
    [window methodForSelector:@selector(setRestorable:)];

  setRestorableFunc(window, @selector(setRestorable:), NO);
}

Not sure whether this is the best option, though.

Upvotes: 0

mity
mity

Reputation: 2349

Try to create a dummy (never used) protocol in some header and make sure it is imported in the source where you use it:

@protocol Compatibility
- (void)setRestorable:(BOOL)flag;
@end

I believe this should persuade the compiler that the class might implement the protocol (even when not explicitly specified in its header) and should stop complaining.

Upvotes: 2

Related Questions