有关SharedInstance的问题 [英] Question regarding SharedInstance

查看:562
本文介绍了有关SharedInstance的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿伙计们,我想问,什么是shareInstance实际上?我的意思是什么用法?



目前我在两个不同文件之间进行通信时遇到了一些问题。



这是我的问题:
我有1个文件调用Ah / Am和另一个文件调用Bh / Bm
啊需要访问Bh中的一些数据,所以....有没有可能的方式我可以实现我想要的吗?
只是想知道它是SharedInstance能够解决我的问题吗?



寻找回复:)

解决方案

sharedInstance可以用于多种方式。



例如,您可以从静态上下文访问对象。实际上它用于支持Singleton模式的大多数方法。
这意味着只需要在整个程序代码中使用该类的一个对象,只需要一个实例。



接口可以如下所示:

  @interface ARViewController 
{
}
@property(nonatomic,retain)NSString * ARName;

+(ARViewController *)sharedInstance;

实施ARViewController:

  @implementation ARViewController 
static id _instance
@synthesize ARName;
...
- (id)init
{
if(_instance == nil)
{
_instance = [[super allocWithZone:nil]在里面];
}
return _instance;
}

+(ARViewController *)sharedInstance
{
if(!_instance)
{
return [[ARViewController alloc] init] ;
}
return _instance;
}

要访问它,请在CustomARFunction类中使用以下内容:

  #importARViewController.h

@implementation CustomARFunction.m

- ( - void)yourMethod
{
[ARViewController sharedInstance] .ARName = @New Name;
}


Hey guys, I wanna ask, what is sharedInstance actually? I mean what is the usage?

Currently I'm having some problem in communicating between 2 different files.

Here's my question: 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? Just wonder is it "SharedInstance" able to solve my problem?

Looking for reply :)

解决方案

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 can look like:

@interface ARViewController
{
}
@property (nonatomic, retain) NSString *ARName;

+ (ARViewController *) sharedInstance;

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;
}

And to access it, use the following in class CustomARFunction:

#import "ARViewController.h"

@implementation CustomARFunction.m

- (void) yourMethod
{
    [ARViewController sharedInstance].ARName = @"New Name";
}

这篇关于有关SharedInstance的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆