Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use respondsToSelector using ARC on Mac

When I call respondsToSelector in an ARC environment, I get the following error message Automatic Reference Counting Issue No known instance method for selector respondsToSelector:

This is the header

#import <AppKit/AppKit.h>


@class MTScrollView;

@protocol MTScrollViewDelegate
-(void)scrollViewDidScroll:(MTScrollView *)scrollView;
@end


@interface MTScrollView : NSScrollView 
{

}

@property(nonatomic, weak) id<MTScrollViewDelegate>delegate;

@end

This is the implementation file

#import "MTScrollView.h"

@implementation MTScrollView

@synthesize delegate;


- (void)reflectScrolledClipView:(NSClipView *)aClipView
{
    [super reflectScrolledClipView:aClipView];

    if([delegate respondsToSelector:@selector(scrollViewDidScroll:)])
    {
        [delegate scrollViewDidScroll:self];
    }
}

@end

Any suggestions on why I am getting this error?

like image 943
David Avatar asked Oct 29 '11 19:10

David


2 Answers

Make the protocol conform to NSObject

@protocol MTScrollViewDelegate <NSObject>

Otherwise the compiler doesn't think that the object will respond to NSObject messages like respondsToSelector, and will generate a warning. It will succeed at runtime without issues either way.

like image 114
Jason Harwig Avatar answered Nov 03 '22 12:11

Jason Harwig


For Swift this becomes:

@objc protocol MTScrollViewDelegate: NSObjectProtocol

The NSObject protocol groups methods that are fundamental to all Objective-C objects.

For more information on what NSObjectProtocol is: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/index.html

like image 40
niket Avatar answered Nov 03 '22 12:11

niket