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

后端 未结 2 1054
一整个雨季
一整个雨季 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: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 
    + (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];
    

提交回复
热议问题