1

I came cross this code as shown below. how could I save existing annotation pins info to NSUserdefault without creating any buttons(IBAction)? Should I put NSUserDefault code into viewWillDisappear? Is that the right way to do it?

To save:

NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
[ud setDouble:location.latitude forKey:@"savedCoordinate-latitude"];
[ud setDouble:location.longitude forKey:@"savedCoordinate-longitude"];
[ud setBool:YES forKey:@"savedCoordinate-exists"];
[ud synchronize];
casillas
  • 16,351
  • 19
  • 115
  • 215

2 Answers2

2

viewWillDisappear is one moment that is often used to save state, but it is not the only place or the only possible place. What if the user suspends your app? You won't get viewWillDisappear. What if viewWillDisappear is not a place where you have access to the annotation information? Perhaps it would better to keep saving info to user defaults as the annotations are created. It depends on the nature and purpose and architecture of your app; it's a problem for you to solve. Your job is to know when your code will run under the event-driven framework, and behave appropriately.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Hello Matt, I got new issue. if you have time, could you take a look at it, please?http://stackoverflow.com/questions/12719865/nsuserdefaults-returns-0-objects – casillas Oct 04 '12 at 03:50
1

You can put that code wherever you want, when you want to save that data. NSUserDefaults is accessible anywhere. Synchronize is what saves it to disk.

Simon Germain
  • 6,834
  • 1
  • 27
  • 42
  • Hello Simon, thanks for answering the question. I would like to know whenever user closes the application, app saves annotations exist on my mapView. Do you think it would be better to put it into viewWillDisappear? My app, once user opens the app, he will see couple of annotations that I thought will be useful, but user may remove any annotations. What would be your suggestion? – casillas Oct 04 '12 at 02:14
  • As Matt said, it would be better to save the annotation at the point of creation. That way, if the user did suspend the app, the data will be saved. – Simon Germain Oct 04 '12 at 02:16
  • Thanks a lot Simon, last question regarding this question but not really fits this topic. How could I save multiple locations into NSUserDefaults? As you seen in the code, I could only save one single annotations, what if I do have more than one? – casillas Oct 04 '12 at 02:24
  • 1
    Here's a great tutorial on how to save arrays to NSUserDefaults: http://stackoverflow.com/questions/537044/storing-custom-objects-in-an-nsmutablearray-in-nsuserdefaults – Simon Germain Oct 04 '12 at 02:27
  • Hello Simon, I got new issue. if you have time, could you take a look at it, please? http://stackoverflow.com/questions/12719865/nsuserdefaults-returns-0-objects – casillas Oct 04 '12 at 03:41