从没有新的Init的类中使用数据 [英] Use Data From Class Without A New Init

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

问题描述

我有一个TabBar布局,在首页选项卡,我有一个按钮连接,当按下时发送一个动作类TransferViewController创建一个GameKit会话。然后我有另一个名为发送的选项卡,其中有一个按钮,说发送文件,当按下时发送一个动作类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.

Model.h

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

Model.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

现在可以使用控制器中的共享会话代码:import 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];

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

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