最近寫了個工具類,用來內建短信、郵件、電話、打開Safari/AppStore、打開相機或相冊,但是寫 delegate 的時候,發現有警告:
Incompatible pointer types assigning to 'id<MFMessageComposeViewControllerDelegate>' from 'Class'
最後,發現,用單例模式才可以。原因:
類方法的self不能充當delegate
下面是
stackoverflow裡解決方法,構造單例模式:
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;
}
最後
- 如果有什麼疑問,可以在評論區一起讨論;
- 如果有什麼不正确的地方,歡迎指導!
注:本文首發于 iHTCboy's blog ,如若轉載,請注明來源。