Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

objective c - What is SharedInstance actually?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...