最近写了个工具类,用来集成短信、邮件、电话、打开Safari/AppStore、打开相机或相册,但是写 delegate 的时候,发现有警告:
Incompatible pointer types assigning to 'id<MFMessageComposeViewControllerDelegate>' from 'Class'
最后,发现,用单例模式才可以。原因:类方法的self不能充当delegate
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];
最后发现,生成单例的方法各不相同,下面是另外一种,至于用那一种更好,或者都一样?简主暂时也不知道。。
##static id _sharedInstance = nil;
+(instancetype)sharedInstance
{
static dispatch_once_t p;
dispatch_once(&p, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
最后
- 如果有什么疑问,可以在评论区一起讨论;
- 如果有什么不正确的地方,欢迎指导!