Transporting data between Appdelegate and Viewcontroller

Asked

Viewed 246 times

3

My problem is this. I need that when the user starts my App, it comes back with the data that was on the screen before closing it. So my initial idea, is when the app enters Background it records a Plist with the information that was on the screen and when it starts again it loads this Plist and sends it to the Viewcontroller where this information is...

But how do I get the information uploaded to Appdelegate to my Viewcontroller?

PS: Feel free to question my solution and/or give a more plausible solution to the problem.

3 answers

3


You do not need to save this information in Appdelegate. In general I advise not to put the logic of the application in this class but to try to separate in modules.
One suggestion would be to forward the notification of the Appdelegate to the Viewcontroller, or better yet, directly listen by notification on your Viewcontroller. To do so, add an Observer in the method -viewDidLoad:

[[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(enteredBackground:) 
    name:UIApplicationDidEnterBackgroundNotification
    object:nil];

The method - (void)enteredBackground:(NSNotification *)notification will be called every time application enters the background and there you put the code to save the information in the plist. Do not forget to remove Observer in -dealloc method.
You can also consider other ways to store the information, such as: Coredata, sqlite, user defaults. To choose the best one you need to analyze the application requirements.

  • It’s just two pieces of information, a Nsstring and a Nsnumber... in case you search for this information saved when the app is started I used UIApplicationDidFinishLaunchingNotification... that’s for sure?

  • ARC does not control this Observer removal? Or do I really need to remove on -dealloc?

  • 1

    If there are only two attributes, saving in Nsuserdefaults is simpler and faster. I do not think it is necessary to read the figures in the Appdelegate. You can do this in -viewDidLoad from Viewcontroller, because if the app is closed, Viewcontroller will be created when the new execution.

  • As for the removal of Observer, it is usually not necessary to do it manually. It depends on when in the life cycle of the VC it was added. For example, add to -viewWillAppear, the right is to remove in the -viewWillDisappear.

2

2

I’ve been using Nsuserdefaults and he can handle it.

To record:

NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
[ud setInteger:1234 forKey:@"senha"];
[ud synchronize];

to read:

NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSInteger SenhaUsuario = [ud integerForKey:@"senha"];

Don’t forget to sync when you update your data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.