Kol*_*ors 2 iphone variables global global-variables save
我正在寻找在我的所有类中全局存储和读取变量的最佳方法.我知道我可以使用'singleton'但是我不确定这是否是存储我的变量的最佳方法或者如何准确地执行此操作?
我使用单身人士,我就是这样做的:
创建一个新类,为此演示我们将其命名MyDataModel.在MyDataModel.h中执行以下操作:
#import <Foundation/Foundation.h>
@interface MyDataModel : NSObject
{
NSString *myStringVariable;
NSUInteger myIntVariable;
//add any variables you need
}
@property (nonatomic, retain) NSString *myStringVariable;
@property (nonatomic) NSUInteger myIntVariable;
+ (MyDataModel *) sharedInstance;
@end
Run Code Online (Sandbox Code Playgroud)
现在在MyDataModel.m中执行:
#import "MyDataModel.h"
@implementation MyDataModel
@synthesize myStringVariable, myIntVariable;
static MyDataModel *_sharedInstance;
+ (MyDataModel *) sharedInstance
{
if(!_sharedInstance)
{
_sharedInstance = [[MyDataModel alloc] init];
}
return _sharedInstance;
}
@end
Run Code Online (Sandbox Code Playgroud)
现在在任何类中你想要使用这个单例,你必须使用#import这个类,这里是如何使用变量:
[MyDataModel sharedInstance].myStringVariable = @"anyThing";
[MyDataModel sharedInstance].myIntVariable = 123;
Run Code Online (Sandbox Code Playgroud)
我希望这能为你澄清一些事情.