Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

model view controller - Inter-ViewController parameters passing in iPhone programming... how to?

I read: 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...