Obj-C - How to pass data between viewcontrollers using a singleton?

后端 未结 2 1388
陌清茗
陌清茗 2020-12-22 14:26

Alright, so this is an extension to a question I asked last night. I have a little firmer grasp on how data can be passed between view controllers using various techniques.

2条回答
  •  一整个雨季
    2020-12-22 15:06

    Your addressing, and memory management is just plain... off. Firstly, there's absolutely no reason to create a singleton for this, but that's beside the point here.

    Secondly, when declaring properties, (atomic, assign) is defaulted to if not otherwise specified, which means your string:

    @property (nonatomic)NSString *passedValue;
    

    is weak sauce, ripe for deallocation and destruction at a moments notice. Declare it copy, strong, or retain.

    Thirdly, there's absolutely no reference to your singleton in the pushed view controller, yet you seem to have the belief that objects that are named the same in different classes retain their value (especially when #import'ed). Not so. You need to reference your singleton and pull the value of [Model sharedModel].passedText into that text field.

    In fact, I fixed your sample in two lines:

    //ViewController2.m
    #import "ViewController2.h"
    
    //actually import the singleton for access later
    #import "Model.h"
    
    @interface ViewController2 () {
        NSString *passedtext;
    }
    @end
    @implementation ViewController2
    @synthesize lbl = _lbl;
    @synthesize passedValue = _passedValue;
    - (void)viewDidLoad
    {
    
     // do code stuff here
        NSLog(@"passedText = %@",passedText);
        //actually reference the singleton this time
        _lbl.text = [Model sharedModel].passedText;
    
        [super viewDidLoad];
    }
    - (void)viewDidUnload
    {
        [self setLbl:nil];
        [super viewDidUnload];
        // Release any retained subviews of the main view.
    }
    - (IBAction)back:(id)sender {
    
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
        ViewController *vc = (ViewController *) [storyboard instantiateViewControllerWithIdentifier:@"welcome"];
        [self presentModalViewController:vc animated:YES];
    }
    @end
    

    Which yields this:

    Fixed the code

提交回复
热议问题