Use Data From Class Without A New Init

前端 未结 1 1118
醉酒成梦
醉酒成梦 2020-12-01 23:18

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

相关标签:
1条回答
  • 2020-12-01 23:27

    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];
    
    0 讨论(0)
提交回复
热议问题