gpt4 book ai didi

objective-c - 单例设计实现

转载 作者:行者123 更新时间:2023-11-28 22:52:22 25 4
gpt4 key购买 nike

根据我之前的问题,here ,我已经调整了我的数据 Controller 类以使用单例设计模式,这样我就可以在多个 View 中只使用一次。但是我确实有几个问题,我似乎也找不到解决方案。

首先,我不确定如何在两个 View 中调用类/对象以使其工作,其次,我已经使用 + 将初始化方法设为全局,但我是否需要对每个方法都这样做?

为了共享数据,我希望能够跨 View 共享的类的初始化是

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

该类使用三个可变数组作为主要内容,需要在两个 View 中设置和读取。

最佳答案

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

  1. 你可以使用类似的东西:

    SpeecherDataController * localReference = [SpeecherDataController instance]; 

    然后是:

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

注意:我想你想在 实例的实现中用 [[SpeecherDataController alloc] init]; 替换 [[self alloc] init];

(另请注意:我无法通过您上面“此处”的链接查看您之前的问题。如果我误解了什么,我深表歉意。)

关于objective-c - 单例设计实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11623962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com