objective-c - 在没有新初始化的情况下使用类中的数据

标签 objective-c ios cocoa-touch class uiviewcontroller

我有一个 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/

相关文章:

ios - 当我使用圆角时,UIImageView 图像被拉伸(stretch)。

ios - 在 objective-C sqlite dao 中读取优先级

ios - 将相机朝它指向的方向移动,同时考虑到旋转

ios - 如何在 iOS 中动态地在 UIView 中制作不同的圆角值?

ios - 名为 "image"的属性没有可见的 ivar 吗?

iphone - 如何在录制视频时以编程方式拍照

ios - Xcode 9.2 + 构建失败 : Invalid bitcode signature

IOS:当应用程序进入后台时,将所有类设置为零

ios - 每次重置标题时如何阻止 UIButton 突出显示/闪烁?

iphone - 如何在 UIPickerView 标签旁边获得复选标记?