私があなたの質問を正しく理解していれば、詳細についてSingleton Design Pattern
はこちらをご覧ください。
したがって、シングルトンを使用すると、グローバル インスタンスを設定し、必要なときに呼び出すことができます。
コードを右クリックして、SingletonClass という名前の Objective-c クラスを追加し、NSObject のサブクラスにします。
以下の例は、必要に応じinteger
て astring
または任意のタイプに変更します。
あなたのSingletonClass.hであなたのSingletonClass.h
#import <Foundation/Foundation.h>
@interface SingletonClass : NSObject
@property int thisIsCounter;
+ (SingletonClass *)sharedInstance;
@end
あなたの SingletonClass.m で
#import "SingletonClass.h"
@implementation SingletonClass
@synthesize thisIsCounter=_thisIsCounter;
+ (SingletonClass *)sharedInstance
{
static SingletonClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[SingletonClass alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
}
- (id)init {
if (self = [super init]) {
// set a singleton managed object , variable in your case
_thisIsCounter=self.thisIsCounter;
}
return self;
}
@end
あなたの場合、そのすべてのクラスであなたの希望するクラスにあなたのシングルトンクラスをインポートしてください
#import "SingletonClass.h"
//in your app delegate when you fetch data increase singleton variable or decrease it if you want , basically you have a global variable that you can use in your all classes
-(IBAction)plus
{
SingletonClass *sharedInstance = [SingletonClass sharedInstance];
sharedInstance.thisIsCounter =sharedInstance.thisIsCounter + 1;
}
コードはテストされていません。必要に応じて改善されました。
//今私を見て!!!!!
上記はグローバルインスタンスを設定し、これを毎秒ビューコントローラーで呼び出すようにします(メインスレッドを使用する必要があり、UIイベントで混乱する可能性があるため、これは注意が必要です)必要:
iOS で定期的に (毎秒) ラベルを更新するにはどうすればよいですか?
UILabel テキストが更新されない
- (void)viewDidLoad
{
[super viewDidLoad];
NSTimer* timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
-(void) updateLabel
{
SingletonClass *sharedInstance = [SingletonClass sharedInstance];
self.button.text= sharedInstance.thisIsCounter;
}