Use Data From Class Without A New Init

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

Leave a Comment