单身设计实施

时间:2012-07-24 04:02:48

标签: objective-c ios singleton global-variables singleton-methods

根据我之前的问题here,我已经调整了我的数据控制器类以使用单例设计模式,这样我就可以在多个视图中使用它一次。但是,我确实有一些问题似乎无法找到解决方案。

首先,我不确定如何在两个视图中调用类/对象以使其工作,其次我用+创建了初始化方法全局,但我是否需要对每个方法执行此操作?

为了共享数据,我希望能够在视图中共享的类的初始化是

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

该类使用三个Mutable Arrays作为主要内容,需要在两个视图中设置和读取。

1 个答案:

答案 0 :(得分:2)

如果我理解你的问题,我认为答案是:

  1. 您可以使用以下内容:

    SpeecherDataController * localReference = [SpeecherDataController instance]; 
    

    然后再说:

    [localReference someMessage:param]; // or ...
    localReference.property = whatever; 
    
  2. 不,你的SpeecherDataController类的方法也不需要成为类方法(即,它们不需要+前缀,它们可以使用{{1如果你想访问其中的ivars。)

  3. 注意:我认为您希望在-的实施中将[[self alloc] init];替换为[[SpeecherDataController alloc] init];

    (另请注意:我无法按照您上面的“此处”链接查看您之前的问题。如果我误解了某些内容,我很抱歉。)