James
James

Reputation: 979

Overwrite and Store Numerical Incremented Value in Variable

So I am just a few months into Objective-c and have been writing a fairly simple program that will prompt the user for a firstName, lastName and let's just say a favoriteColor. I then have these user inputs stored via outputting the contents to a .txt file. Each time the program is executed, a person object (with a full name and favorite color) is added to the list in a .txt file via the NSOutputStream class.

What I want to do is have a sequential ticket system in place. So each time the program is executed, a ticket number (lets call this variable topTicket for clarity's sake) is assigned to the new person object and printed out as an ID of sorts along with the name and color.

So let's say after the first 2 times I run my project that the text file contains the following:

FAVORITE COLOR INVENTORY

Name:  John Doe
Favorite Color:  Red
Ticket:  #031354

Name:  Jane Doe
Favorite Color:  Blue
Ticket:  #031355

Then i want the ticket variable (topTicket) to be the following next time I open my project files:

topTicket = 031356

I would like to know how I can have the program overwrite this initial value each time it is executed. Therefor the next time I open up my project in xCode, after having run it once earlier in the day, the topTicket will now be one more than it was before (031354 in this case), having incremented itself and overwritten the previous value. That way all I have to do is call this topTicket variable every time when writing to the .txt file instead of requiring user input.

I hope I am making sense. I would love any suggestions or guidance as to how I should go about this. ...maybe I am overthinking things haha.

Upvotes: 0

Views: 40

Answers (1)

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16660

One way to accomplish that is to use NSUserDefaults. You can store a value with -setInteger:forKey: and read a value with -intergerForKey:. Sample code:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger ticketNumber = [defaults integerForKey:@"lastTicketNumber"];
ticketNumber++;
// use it
[defaults setInteger:ticketNumber forKey:@"lastTicketNumber"];

I think at one point in your project you want to save all data including user data. In that case you should save the ticket number at a place, where you store the other data, whatever it is. This is to keep data consistently.

Upvotes: 1

Related Questions