C.Johns
C.Johns

Reputation: 10245

objective c counter

I want to create a counter that is remembered for the life of the application, i.e. never forgotten, unless the application is uninstalled.

The counter is going to keep track of the number of requests the user makes... maybe I will look to reset it when it gets too big, but by and large it will just keep incrementing every time a request is made.

It needs to be of type UInt32. My main concern is: How do I save this value? I'm assuming that it's going to have to be saved in the plist. I have not had any experience with plists. I'm hoping someone might be able to supply some example code of how to save to the plist etc, and then maybe a tutorial link to working with plists. I am currently looking, but maybe someone has something they have had success with in the past.

Upvotes: 1

Views: 1057

Answers (2)

bneely
bneely

Reputation: 9093

Save it in NSUserDefaults. NSUserDefaults is easy to learn; you only need a few lines of code. Try using two variables:

UInt32 count
UInt32 fourBillion

Since UInt32 has a maximum value slightly more than 4 billion, you can increment count until it reaches four billion, then for the next increment, set count to 0 and increment fourBillion.

Then to get the true count, you multiply fourBillion by 4,000,000,000, then add count. Be sure to use a data type that can store the maximum possible value. This lets you store a staggeringly huge number; probably far more than you need.

Upvotes: 0

rsez
rsez

Reputation: 351

NSUserDefaults is the way to go.

NSString * yourKey = @"someKey";
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:[defaults integerForKey:yourKey] + 1 forKey:yourKey]

Upvotes: 5

Related Questions