Use Data From Class Without A New Init

2019-01-09 14:32发布

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.

1条回答
淡お忘
2楼-- · 2019-01-09 14:54

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

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];
查看更多
登录 后发表回答