What is SharedInstance actually?

前端 未结 4 1805
礼貌的吻别
礼貌的吻别 2020-12-17 01:49

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:<

4条回答
  •  Happy的楠姐
    2020-12-17 02:30

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

提交回复
热议问题