美文网首页
关于IOS如何在类方法里使用全局变量

关于IOS如何在类方法里使用全局变量

作者: Style_伟 | 来源:发表于2016-08-23 22:38 被阅读4890次

    开发过程中,我们经常会定义一些工具类,分类等,这些方法调用方便,代码简洁,开发起来省事省力,但是也会遇到一些问题,有些类方法中必须使用变量来保存一些东西,这时候就遇到难题了,因为经常使用的属性变量是属于对象的,必须有实际的对象才能调用变量,而类方法是不创建对象而直接调用方法的。这时候我们需要另一种变量去保存数据,就是全局变量。

    • static修饰的全局变量是可以使用的
    
       static NSMutableDictionary *_soundIDs;
    
        + (void)initialize
         {
             _soundIDs = [NSMutableDictionary dictionary];
        }
    
        //  + (NSMutableDictionary *)soundIDs
        //  {
        //    if (_soundIDs == nil) {
        //        _soundIDs = [NSMutableDictionary dictionary];
        //    }
        //    
        //    return _soundIDs;
        //   }
    
    • initialize 是第一次使用的时候直接执行的,也可以使用类方法来懒加载static静态变量,这样在代码中就可以使用这个变量了。
         + (void)playSoundWithSoundname:(NSString *)soundname
    {
        // 1.定义SystemSoundID
        SystemSoundID soundID = 0;
        
        // 2.从字典中取出对应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);
    }
    
    

    相关文章

      网友评论

          本文标题:关于IOS如何在类方法里使用全局变量

          本文链接:https://www.haomeiwen.com/subject/mxpnsttx.html