Search code examples
iosstoryboardseguecorruption

iOS Storyboard clobbering variables when pushing scenes? Why? How should it be done?


I have the following storyboard configuration in my iOS project.

storyboard1->NavController-sceneA->stoyboard2/initialview

storyboard2->sceneB->sceneC

-> is a "show" segue Scene A loads a storyboard and pushes it onto its navigation controller.

  • Scene A has a controller that instances class X.
  • Scene B uses the default UIViewControoler Class.
  • SceneC has a controller that instances class Y.

The implementations for both classes are as follows

//ClassX.h//
@interface ClassX : UITableViewController

//ClassX.m//
@implementation ClassX
NSArray* model;

//..
@end


//ClassY.h//
@interface ClassY : UITableViewController

//ClassY.m//
@implementation ClassY
NSArray* model;

//..
@end

The problem is that when I try to load scene C, it tries to use the field called "model" in its implementation– but gets the field of the model for scene A for some reason. Why is this and how should I correct it?


Solution

  • You should make model a property of the classes rather than declaring them as you do. They are probably creating global variables. Or declare them inside {} after @implementation to make sure they are variables which are part of the class.

    So either:

    @implementation{
      NSArray *model
    }
    ...
    @end
    

    or better use private properties and use self.model in the code.:

    So in classY.m try:

    @interface ClassY ()
       @property NSArray *model;
    @end
    
    @implementation ClassY
    ...
    @end
    

    Do the same for ClassX.