最近寫了個工具類,用來集成短信骑丸、郵件、電話妒貌、打開Safari/AppStore通危、打開相機或相冊,但是寫 delegate 的時候灌曙,發(fā)現(xiàn)有警告:
Incompatible pointer types assigning to 'id<MFMessageComposeViewControllerDelegate>' from 'Class'
最后菊碟,發(fā)現(xiàn),用單例模式才可以在刺。原因:類方法的self不能充當delegate
下面是stackoverflow里解決方法框沟,構(gòu)造單例模式:
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];
最后發(fā)現(xiàn)藏古,生成單例的方法各不相同,下面是另外一種忍燥,至于用那一種更好拧晕,或者都一樣?簡主暫時也不知道梅垄。厂捞。
##static id _sharedInstance = nil;
+(instancetype)sharedInstance
{
static dispatch_once_t p;
dispatch_once(&p, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
最后
- 如果有什么疑問,可以在評論區(qū)一起討論队丝;
- 如果有什么不正確的地方靡馁,歡迎指導!
注:本文首發(fā)于 iHTCboy's blog机久,如若轉(zhuǎn)載臭墨,請注明來源。