我有一个 TabBar 布局,在“主页”选项卡中我有一个“连接”按钮,按下该按钮时会向 TransferViewController 类发送一个操作以创建 GameKit session 。然后我有另一个名为“发送”的选项卡,其中有一个按钮,上面写着“发送文件”,按下该按钮时,会向 TransferViewController 类发送一个操作,该类还使用使用 connect 设置的“ session ”变量来发送文件,但因为它是不同的它创建了一个新的 Controller 实例,并希望我再次连接,但该按钮位于“主页”选项卡上。
无论如何,我可以在没有两个实例的情况下为两个选项卡使用一个 Controller 吗?我希望用户单击“主页”选项卡上的“连接”,然后切换到“发送”选项卡,然后按“发送文件”并使用另一个选项卡上的连接设置的变量。如果这令人困惑,我很抱歉。
最佳答案
这一点也不令人困惑 - 事实上,这种情况一直都会出现。在模型- View - Controller 系统中的工作方式是,您设置一个模型类,使其成为单例,并在需要共享数据的所有 Controller 中添加对该单例的引用。
模型.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
现在您可以在 Controller 代码中使用共享 session :导入"Model.h"
,然后编写
[[Model instance].session connect];
[[Model instance].session sendAction:myAction];
关于objective-c - 在没有新初始化的情况下使用类中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11944891/