在没有新初始化的情况下使用类中的数据 [英] Use Data From Class Without A New Init

查看:28
本文介绍了在没有新初始化的情况下使用类中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 TabBar 布局,在主页选项卡中我有一个按钮连接",按下该按钮时会向类 TransferViewController 发送一个动作以创建一个 GameKit 会话.然后我有另一个名为 Send 的选项卡,它有一个按钮,上面写着发送文件",按下它时会向类 TransferViewController 发送一个动作,它也使用使用连接设置的会话"变量来发送文件,但因为它是不同的选项卡,它创建了控制器的一个新实例,它希望我再次连接,但按钮位于主页选项卡上.

I have a TabBar layout and in the Home tab i have a button "Connect" which when pressed sends an action to the class TransferViewController to create a GameKit Session. Then i have another tab called Send which has a button that says "Send File" which when pressed sends an action to the class TransferViewController also which uses the "Session" variable that was setup using connect to send a file but since it is a different tab it creates a new instance of the Controller and it wants me to connect again but the button is on the Home tab.

无论如何,我可以在没有两个实例的情况下为两个选项卡使用一个控制器吗?我希望用户单击主页"选项卡上的连接",然后切换到发送"选项卡并按发送文件",并通过另一个选项卡上的连接"使用变量设置.如果这令人困惑,我很抱歉.

Is there anyway that I can have one Controller for two tabs without having two instances? I want the user to click connect on the Home tab then switch to the Send tab and press Send File and use the variables setup by connect on the other tab. I'm sorry if this is confusing.

推荐答案

这一点都不令人困惑——事实上,这种情况一直出现.这在模型-视图-控制器系统中的工作方式是设置一个模型类,使其成为单例,然后在需要共享数据的所有控制器中添加对该单例的引用.

This is not confusing at all - in fact, this comes up all the time. The way this works in model-view-controller systems is that you set up a model class, make it a singleton, and add references to that singleton in all controllers that need to share the data.

模型.h

@interface Model : NSObject
@property (nonatomic, readwrite) Session *session;
-(id)init;
+(Model*)instance;
@end

模型.m

@implementation Model
@synthesize isMultiplayer;

-(id)init {
    if(self=[super init]) {
        self.session = ...; // Get the session
    }
    return self;
}

+(Model*)instance {
    static dispatch_once_t once;
    static Model *sharedInstance;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}
@end

现在您可以在控制器代码中使用共享会话:导入 "Model.h",然后编写

Now you can use the shared session in your controller code: import "Model.h", and write

[[Model instance].session connect];
[[Model instance].session sendAction:myAction];

这篇关于在没有新初始化的情况下使用类中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆