What is SharedInstance actually?(SharedInstance 实际上是什么?)
问题描述
sharedInstance 实际上是什么?我的意思是有什么用途?
What is sharedInstance actually? I mean what is the usage?
目前我在 2 个不同的文件之间进行通信时遇到了一些问题.
Currently I'm having some problem in communicating between 2 different files.
这是我的问题:
我有 1 个文件调用 A.h/A.m
和另一个文件调用 B.h/B.m
.A.h
需要访问 B.h
中的一些数据,所以....有什么方法可以实现我想要的吗?
I have 1 file call A.h/A.m
and another file call B.h/B.m
. A.h
need to access some of the data in B.h
, so .... is there any possible way I could achieve what I want?
只是想知道它是SharedInstance"吗?能解决我的问题吗?
Just wonder is it "SharedInstance" able to solve my problem?
推荐答案
sharedInstance 有多种用途.
sharedInstance could be used for several ways.
例如,您可以从静态上下文中访问对象.实际上,它用于支持单例模式的大多数方式.这意味着在整个程序代码中只使用该类的一个对象,完全只使用一个实例.
For example you can access an object from a static context. Actually it is used most ways for supporting the Singleton-pattern. That means that just one object of the class is used in your whole program code, just one instance at all.
界面可能如下所示:
@interface ARViewController
{
}
@property (nonatomic, retain) NSString *ARName;
+ (ARViewController *) sharedInstance;
实现ARViewController:
Implementation ARViewController:
@implementation ARViewController
static id _instance
@synthesize ARName;
...
- (id) init
{
if (_instance == nil)
{
_instance = [[super allocWithZone:nil] init];
}
return _instance;
}
+ (ARViewController *) sharedInstance
{
if (!_instance)
{
return [[ARViewController alloc] init];
}
return _instance;
}
要访问它,请在 CustomARFunction 类中使用以下代码:
And to access it, use the following in class CustomARFunction:
#import "ARViewController.h"
@implementation CustomARFunction.m
- (void) yourMethod
{
[ARViewController sharedInstance].ARName = @"New Name";
}
这篇关于SharedInstance 实际上是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!