views:

404

answers:

1

I read: http://stackoverflow.com/questions/2363777/iphone-how-to-pass-data-between-several-viewcontrollers-in-a-tabbar-app and was wondering what is the difference between

[[UIApplication sharedApplicaton] delegate]

and

extern struct* global

?

Conceptually, I don't see how [[UIApplication sharedApplicaton] delegate] not being a global thing. In fact, that lessen the sense of guilty when using the dirty global struct * now.

I am starting a new project very soon. So, I use this break to ask the question: is there any best-practice code example to illustrate how to share data between two ViewControllers (but not globally)?

Let me put it in an example:

  • this is a game
  • there is a NSString *name to store the player's name
  • there is a NSInteger score to store the player's current score
  • the GameMainViewController will update and display the score
  • in the GameSettingViewController, there is a text field to edit name and a button to reset score
  • the GameMainViewController is responsible for set a default name (if nil), save both name and score when exit, load both (if exists) when start

so

  • where should I put "name" and "score"?
  • how can both ViewControllers access and change the values

Thank you!

+1  A: 

You can store name and score in NSUserDefaults.

Retrieve an item:

NSString *name = [[NSUserDefaults standardUserDefaults]objectForKey:@"name"];

Setting an item:

[[NSUserDefaults standardUserDefaults]setObject:@"Horace" forKey:@"name"];

Also, if this is data that you want to preserve across launches of the app, you may want to archive it into a plist.

christo16