Question

App Overview:

A user can perform Internet speed tests and other types of test with varied results. Typically results for a test are stored in NSArrays and NSStrings.

Aim:

I'm trying to create a history system that allows a user to go back and view past results.

Problem:

I'm having a hard time figuring out which storage medium to use and how it all should fit together.

Is there a way to name NSUserDefaults using a String or Integer value? For example I have a string called "hisName" with a value of "history1", would it be possible to name the NSUserDefaults *hisName but have it revert to the value history1? The idea being with each test the number increments and a new history defaults is created (history2, history 3 etc.).

In the Android version of this app this is possible. So the app simply creates "History-X" on the fly depending on the max number of history allowed. When the max is reached the first is overwritten.

UPDATE:

I'll try a bit harder to explain what I'm getting at.

The user finishes a test and I store all the required data in an NSUserDefaults/NSDictionary file named History1.

I then increment the value of an Integer called HistoryCount to 2. Now when the user performs another test I want to call the NSUserDefaults/NSDictionary "History2" where the 2 comes from the Integer HistoryCount. I can't find a way to name NSUserDefaults/NSDictionary with an NSString etc.

Was it helpful?

Solution

Use this method to save the dictionary;

-(void)saveDefaults:(int)historyCount{
    NSDictionary *history1 = [NSDictionary dictionary]; //You already have this dictionary
    NSString *historyKey = [NSString stringWithFormat:@"history%d",historyCount];
    [[NSUserDefaults standardUserDefaults] setObject:history1 forKey:historyKey];
}

So your code might look somewhat like this;

self.historyCount =1;

[user runTest]; //first run 
[user saveDefaults:self.historyCount];
self.historyCount++;


[user runTest];
[user saveDefaults:self.historyCount];
self.historyCount++;

and so on..

If you want multiple history dictionary objects for the same user then you can store the group of history objects as an array (use index to access the history objects) or you could use a dictionary with key like @"history1" and value, the history1 dictionary. You can generate new keys like shown above.

But if you have multiple users and many history objects for each user , it might get hard to keep track of. Instead you can use core-data for object persistence/management.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top