Incompatible pointer types assigning to 'id' from 'Class'

后端 未结 2 1053
一整个雨季
一整个雨季 2021-02-04 11:34

I have a \"Utility\" class that implements the AVAudioPlayerDelegate protocol.

This is my Utility.h

@i         


        
相关标签:
2条回答
  • 2021-02-04 12:12

    When you don't need an instance of a Class, just manually get ride of the warning:

    audioPlayer.delegate = (id<AVAudioPlayerDelegate>)self;
    

    On the other hand, please note that if you need a Delegate, it means you should have an instance of a Class as a good coding practice instead of a static Class. It can be made a singleton easily:

    static id _sharedInstance = nil;
    +(instancetype)sharedInstance
    {
        static dispatch_once_t p;
        dispatch_once(&p, ^{
            _sharedInstance = [[self alloc] init];
        });
        return _sharedInstance;
    }
    
    0 讨论(0)
  • 2021-02-04 12:14

    You've declared your method as a class method, and you're trying to use the Class object as the delegate. But you can't add protocols to Class objects.

    You need to change playAudioFromFileName:... to an instance method and create an instance of Utility to use as the delegate. Maybe you want to have a single instance of Utility shared by all callers. This is the Singleton pattern, and it's pretty common in Cocoa. You do something like this:

    Utility.h

    @interface Utility : NSObject <AVAudioPlayerDelegate>
    + (Utility *)sharedUtility;
    @end
    

    Utility.m

    @implementation Utility
    
    + (Utility *)sharedUtility
    {
        static Utility *theUtility;
        @synchronized(self) {
            if (!theUtility)
                theUtility = [[self alloc] init];
        }
        return theUtility;
    }
    
    - (void)playAudioFromFileName:(NSString *)name ofType:(NSString *)type withPlayerFinishCallback:(SEL)callback onObject:(id)callbackObject
    {
        ... 
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: [self getResourceURLForName:name ofType:type] error: nil];
        audioPlayer.delegate = self;
        ...
    }
    
    @end
    

    Usage

    [[Utility sharedUtility] playAudioFromFileName:@"quack" ofType:"mp3" withPlayerFinishCallback:@selector(doneQuacking:) onObject:duck];
    
    0 讨论(0)
提交回复
热议问题