开发者

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 s开发者_开发问答ee 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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜