How do I share an object between UIViewControllers on iPhone?

前端 未结 5 732
清酒与你
清酒与你 2020-11-28 22:48

My application is a tab bar application, with a separate view controller for each tab.

I have an object in my first view controller (A) which contains all my stored

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 23:07

    One option you have is to declare your date model as instance variables of your app delegate (as mentioned by other commenters).

    Instead of referencing the app delegate as suggested by nevan an alternative is to add a property to your view controller classes (A and B) for your data model.

    Say you wanted to share a data model object between your view controllers you can add a property to each:

    @interface AViewController : UIViewController {
        MyDataModel *model;
    }
    
    @property (nonatomic, retain) MyDataModel *model;
    
    @end
    
    @interface BViewController : UIViewController {
        MyDataModel *model;
    }
    
    @property (nonatomic, retain) MyDataModel *model;
    
    @end
    

    When you initialise your view controller you can then set this property to the object context initialised previously.

    You have mentioned a tab bar controller. If your view controllers are wired through IB all you have to do is to set these parameters in your application delegate applicationDidFinishLaunching: method, before the tab bar controller is displayed:

    @interface MyAppDelegate : NSObject 
    {
    
        MyDataModel *model;
        AViewController *aViewController;
        BViewController *bViewController;
        ...
    }
    
    @property (retain) IBOutlet AViewController *aViewController;
    @property (retain) IBOutlet BViewController *aViewController;
    
    @end
    
    @implementation MyAppDelegate
    
    ...
    
    - (void)applicationDidFinishLaunching:(UIApplication *)application
    {
    ...
    
        aViewController.model = model;
    
        bViewController.model = model;
    
        [window addSubview:tabBarController.view];
        [window makeKeyAndVisible];
    }
    

    Don't forget to release the model in your view controller's dealloc method.


    The alternative is to use a singleton object. An simple singleton example:

    @interface MyDataModel : NSObject
    {
    }
    
    + (MyDataModel *) sharedDataModel;
    
    @end
    
    @implementation MyDataModel
    
    static MyDataModel *sharedDataModel = nil;
    
    + (MyDataModel *) sharedDataModel
    {
    
        @synchronized(self)
        {
            if (sharedDataModel == nil)
            {
                sharedDataModel = [[MyDataModel alloc] init];
            }
        }
        return sharedDataModel;
    }
    
    @end
    

    You can access this data model from all your view controllers with something similar to the following:

    MyDataModel *model = [MyDataModel sharedDataModel];
    

    See also this stack overflow discussion about singletons.

提交回复
热议问题