Singleton Design Implementation

86 Views Asked by At

As per my previous question, here, I've adapted my Data Controller class over to use a singleton design pattern so that I can use it only once across multiple views. However I do have a couple question I can't seem to find the solution too.

Firstly I'm not exactly sure how to call the class/object in the two views to make it work, and secondly I've made the initialisation method global with + but do I need to do this with each of the methods?

The initialisation of of the class that I want to be able to share across the views, in order to share the data, is

static SpeecherDataController *_instance = nil;  // <-- important 

+(SpeecherDataController *)instance
{ 
    // skip everything
    if(_instance) return _instance; 

    // Singleton
    @synchronized([SpeecherDataController class]) 
    {
        if(!_instance)
        {
            _instance = [[self alloc] init];

            //  NSLog(@"Creating global instance!"); <-- You should see this once only in your program
        }

        return _instance;
    }

    return nil;
}

The class uses three Mutable Arrays as the main content which need to be both set and read in the two views.

1

There are 1 best solutions below

1
On BEST ANSWER

If I understand your questions correctly, I think the answers are:

  1. You can use something like:

    SpeecherDataController * localReference = [SpeecherDataController instance]; 
    

    and then later:

    [localReference someMessage:param]; // or ...
    localReference.property = whatever; 
    
  2. No, the methods on your SpeecherDataController class do not also need to be made class methods (i.e., they do not need to have the + prefix, they can use - if you want to access ivars within them).

Note: I think you want to replace [[self alloc] init]; with [[SpeecherDataController alloc] init]; in your implementation of instance.

(Also, note: I was unable to follow your link to "here" above to see your previous question. So my apologies if I misunderstood something.)