ios - 创建全局变量的最佳实践

标签 ios objective-c iphone xcode global-variables

我正在研究 IOS 静态库。 我需要创建只能在此库中访问的全局变量。 我知道 3 种方法来做到这一点

问题是,哪种方式更好。


第一个解决方案:SharedInstance

.h:

  @interface GlobalVars : NSObject
    @property  int counter;
    +(instancetype)sharedInstance;
@end

.m:

 @implementation GlobalVars
    +(instancetype)sharedInstance {

        static dispatch_once_t p = 0;
        __strong static id _sharedObject = nil;
        dispatch_once(&p, ^{
            _sharedObject = [[self alloc] init];
        });
        return _sharedObject;
    }

    +(int)counter{
    return [GlobalVars sharedInstance].counter;
    }

    +(void)setCounter:(int)_counter{
    [GlobalVars sharedInstance].counter=_counter;
    }
@end

在代码中使用:

  [GlobalVars setCounter:5];
    int i= GlobalVars.counter

方案二:静态变量+类方法

h:

 @interface GlobalVars
 + (int) counter;
 + (void) setCounter:(int)val;
 @end

米:

 @implementation GlobalVars
 static int value;
+ (int) counter {   
 return value;
   }

+ (void) setCounter:(int)val {
 value = val; 
 }
     @end

在代码中使用:

   [GlobalVars setCounter:5];
    int i= GlobalVars.counter

第三种方案:外部变量

常量.h:

extern int *kCounter ;

在代码中使用:

#import "Constants.h"
-(void)someMethod{
kCounter=5;
int i=kCounter;
}

谢谢

编辑: 解决方案必须是“线程安全的”

最佳答案

对于大多数类型,您可以使用 NSUserDefaults。在 AppDelegate 中,您可以注册默认值并稍后从任何范围修改它们。

Example

保存

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];

// saving an NSInteger
[prefs setInteger:42 forKey:@"integerKey"];

// saving a Double
[prefs setDouble:3.1415 forKey:@"doubleKey"];

// saving a Float
[prefs setFloat:1.2345678 forKey:@"floatKey"];

// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];

检索

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// getting an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];

// getting an NSInteger
NSInteger myInt = [prefs integerForKey:@"integerKey"];

// getting an Float
float myFloat = [prefs floatForKey:@"floatKey"];

关于ios - 创建全局变量的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27960101/

相关文章:

ios - Swift Associative Enum 在 fallthrough 中使用参数

ios - 快速滚动表格 View 时,原型(prototype)单元格会摇晃或颤抖

ios - 使用 UIScrollView 的简单图片库

ios - 如何在 Objective c 的 alertview 中创建 Tableview

iphone - 在对象数组中使用数据

iphone - 有什么方法可以获取 iPhone 用户的姓名?

iphone - 将多个文件复制到文档目录

ios - Storyboard在不同时间显示多个 View

ios - Apple - iOS - 使用 XCode 8.2.1 在 iOS 10.3 上进行测试

iphone - 检查文本字段文本是否几乎等于字符串