Make a Counter

Discussion in 'iOS Programming' started by Josh Kahane, May 12, 2009.

  1. Josh Kahane macrumors 6502

    Joined:
    Aug 29, 2006
    Location:
    Suffolk, UK
    #1
    Hi

    So I have my app, but I want a counter so that when I press a button it will add 1 onto the number count. Also I want this number to be stored so that when you quit the app and re open it the number is still there so it makes a record. I cant quite get my head around how to do this and would appreciate any help, thank you.
     
  2. BlackWolf macrumors regular

    Joined:
    Apr 9, 2009
    #2
    well, I don't quite know how to explain this because I am not sure how much experience you have. It sounds like you havn't THAT much experience. I will give you a brief explanation how I would do it. You can find a lot of infos in apple's examples and if you have further questions post them here:

    1) create an instance variable of type int in the UIViewController that displays the button and the counter

    2) when the UIViewController is created, set that variable to 0

    3) create a method that increases the variable by one and then displays it in a label

    4) link that method to the button so it is executed when the button is pressed

    5) To save the counter, you have to create an NSUserDefaults object ... read the manual of NSUserDefaults to see how it works. if you need further help I will give you a sample code

    thats's it :)
     
  3. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #3
    Well, you've got the incrementing of the counter working, yes?

    So, for the second part, to me the easiest way to achieve saving a setting and restoring it upon application rerun is to store the value in [NSUserDefaults standardUserDefaults].
     
  4. Josh Kahane thread starter macrumors 6502

    Joined:
    Aug 29, 2006
    Location:
    Suffolk, UK
    #4
    Well thanks, thats a nice little overview. It has certainly cleared up how I would go about doing that.

    I have had a shot at it but can't quite refine what I'm ding so if you could send me or attach a sample source code for it I would really very much appreciate it.
     
  5. BlackWolf macrumors regular

    Joined:
    Apr 9, 2009
    #5
    I'm normally not that big of a fan of handing out sample codes because ... well, you don't normally learn much from that.

    try to do what I posted step by step. the moment you don't know what to do or are unsure how to do something post it ... . a little help:

    1) should be no problem (hopefully). if it is, you should really learn the basics of objective C!

    2) normally, UIViewControllers have a viewDidLoad method that is executed, well, when the view did load :D that's where you want to set your instance variables to standard values
     

Share This Page