開發(fā)過程中言疗,我們經(jīng)常會(huì)定義一些工具類晴圾,分類等,這些方法調(diào)用方便噪奄,代碼簡潔死姚,開發(fā)起來省事省力人乓,但是也會(huì)遇到一些問題,有些類方法中必須使用變量來保存一些東西都毒,這時(shí)候就遇到難題了色罚,因?yàn)榻?jīng)常使用的屬性變量是屬于對象的,必須有實(shí)際的對象才能調(diào)用變量账劲,而類方法是不創(chuàng)建對象而直接調(diào)用方法的戳护。這時(shí)候我們需要另一種變量去保存數(shù)據(jù),就是全局變量瀑焦。
- static修飾的全局變量是可以使用的
static NSMutableDictionary *_soundIDs;
+ (void)initialize
{
_soundIDs = [NSMutableDictionary dictionary];
}
// + (NSMutableDictionary *)soundIDs
// {
// if (_soundIDs == nil) {
// _soundIDs = [NSMutableDictionary dictionary];
// }
//
// return _soundIDs;
// }
- initialize 是第一次使用的時(shí)候直接執(zhí)行的腌且,也可以使用類方法來懶加載static靜態(tài)變量,這樣在代碼中就可以使用這個(gè)變量了榛瓮。
+ (void)playSoundWithSoundname:(NSString *)soundname
{
// 1.定義SystemSoundID
SystemSoundID soundID = 0;
// 2.從字典中取出對應(yīng)soundID,如果取出是nil,表示之前沒有存放在字典
soundID = [_soundIDs[soundname] unsignedIntValue];
if (soundID == 0) {
CFURLRef url = (__bridge CFURLRef)[[NSBundle mainBundle] URLForResource:soundname withExtension:nil];
AudioServicesCreateSystemSoundID(url, &soundID);
// 將soundID存入字典
[_soundIDs setObject:@(soundID) forKey:soundname];
}
// 3.播放音效
AudioServicesPlaySystemSound(soundID);
}