不兼容的指针类型分配给'id< AVAudioPlayerDelegate>'来自'班级' [英] Incompatible pointer types assigning to 'id<AVAudioPlayerDelegate>' from 'Class'
问题描述
我有一个实用程序类来实现 AVAudioPlayerDelegate 协议。
I have a "Utility" class that implements the AVAudioPlayerDelegate protocol.
这是我的 Utility.h
@interface Utility : NSObject <AVAudioPlayerDelegate>
{
}
这是它的对应 Utility.m
@implementation Utility
static AVAudioPlayer *audioPlayer;
+ (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; // this is the line that causes the Warning
...
}
我的iOS应用程序运行良好,但是在迁移到iOS5和XCode 4.2后,编译器开始抛出此警告,位于 audioPlayer.delegate = self;
行:
My iOS application works well, however after migrating to iOS5 and XCode 4.2 the compiler started throwing this warning, located at the audioPlayer.delegate = self;
line:
Incompatible pointer types assigning to id <AVAudioPlayerDelegate> from 'Class'
我怎么能摆脱它?
推荐答案
您已将方法声明为类方法,并且您尝试使用Class对象作为委托。但您无法向Class对象添加协议。
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.
您需要将 playAudioFromFileName:...
更改为实例方法并创建实用程序
的实例以用作委托。也许您希望所有呼叫者共享一个 Utility
的实例。这是Singleton模式,在Cocoa中很常见。你做这样的事情:
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:
@interface Utility : NSObject <AVAudioPlayerDelegate>
+ (Utility *)sharedUtility;
@end
Utility.m
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];
这篇关于不兼容的指针类型分配给'id< AVAudioPlayerDelegate>'来自'班级'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!