0

I have a JSON request which returns different parameters, name for example. I would like to cache a variable for the name parameter, which I can view in the app later.

For example: name from JSON request = david. the variable is called firstname. firstname should equal "david". firstname should be stored so I can view it in all parts of my apps.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
tracifycray
  • 1,423
  • 4
  • 18
  • 29
  • 2
    This is broad, you could use NSUserDefaults, you could use CoreData, you store it in memory as a singleton if it is only needed for the life of the app. – Tim Oct 24 '13 at 19:28
  • possible duplicate of [Save string to the NSUserDefaults?](http://stackoverflow.com/questions/3074483/save-string-to-the-nsuserdefaults) – RyanR Oct 24 '13 at 19:32

3 Answers3

2

For something simple as a string, the quick and dirty solution is to store it in NSUserDefaults.

Storing

[[NSUserDefaults standardDefaults] setObject:firstname forKey:@"kUserFirstName"];
[[NSUserDefaults standardDefaults] synchronize];

Retrieving

NSString *string = [[NSUserDefaults standardDefaults] objectforKey:@"kUserFirstName"];

If it gets more complicated than that, you have to consider a more structured persistence store. A valid option is CoreData.

There exist a few frameworks that might help you in storing JSON resources in CoreData, the most interesting being RestKit.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
1

First off, you might consider checking out RestKit as it successfully accomplishes a whole slew of server interaction and CoreData persistence in iOS.

I'm a little short on time (on a lunch break here) so I'll just lazily post an example from an app I have.

- (void)loadFiltersFromJSON {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"FreeFilterBank" ofType:@"json"];
    NSData *filterData = [NSData dataWithContentsOfFile:path];

    NSError *err;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:filterData options:kNilOptions error:&err];
    if (err) { //TODO this can be removed prior to shipping the app
        NSLog(@"%@", err);
    }
    NSArray *definedFilters = [json objectForKey:@"Filter"];
    NSManagedObjectContext* moc = [self managedObjectContext];

    for (NSDictionary *filter in definedFilters) {
        NSString *name = [filter valueForKey:@"name"];
        BOOL exists = [self alreadyExists:name inManagedObjectContext:moc];
        if (!exists) {
            NSString *imageNamed = [filter valueForKey:@"imageName"];
            NSString *filterDesignator = [filter valueForKey:@"filterDesignator"];
            NSString *paid = [filter valueForKey:@"paidOrFree"];
            [self createFilterWithName:name imageNamed:imageNamed  filterDesignator:filterDesignator paidOrFree:paid];
        }
    }


}

- (BOOL)alreadyExists:(NSString*)filterNamed inManagedObjectContext:(NSManagedObjectContext*)moc {
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"name == %@", filterNamed];
    NSEntityDescription* description = [NSEntityDescription entityForName:@"Filter" inManagedObjectContext:moc];
    NSFetchRequest* request = [[NSFetchRequest alloc] init];
    [request setEntity:description];
    [request setPredicate:predicate];
    NSError* error;
    NSArray* fetchedResult = [moc executeFetchRequest:request error:&error];
    if (error) {
        NSLog(@"%@",error.localizedDescription);
    }

    if (fetchedResult.count == 0) {
        return NO;
    }
    else {
        return YES;
    }

}

- (void)createFilterWithName:(NSString*)name imageNamed:(NSString*)imageName filterDesignator:(NSString*)designator paidOrFree:(NSString *)paid {
    NSManagedObjectContext* moc = [self managedObjectContext];
    Filter* newFilter = [NSEntityDescription insertNewObjectForEntityForName:@"Filter" inManagedObjectContext:moc];
    newFilter.name = name;
    newFilter.imageName = imageName;
    newFilter.filterDesignator = designator;
    newFilter.paidOrFree = paid;

    NSError* error;
    [moc save:&error];
    if (error) {
        NSLog(@"%@",error.localizedDescription);
    }
}

TL;DR This loads data from a JSON stored in the bundle, checks the SQLite data store to see if we already have something with the same name, and creates a new persistent instance of this object if we don't.

Take this example for what you will, there are many many more invocations for serialized data pulled from the web and persistent data within iOS beyond this one example.

ryan cumley
  • 1,901
  • 14
  • 11
  • Regardless of whether your current project is served best by NSUserDefaults or CoreData. I really really recommend getting familiar with CoreData, it's extremely useful in a very wide range of situations, not least because of the fact that persistent data is much more robust at handling app interruptions & background / foreground transitions. – ryan cumley Oct 24 '13 at 20:18
0

The easiest way is to use NSUserDefaults and set the key to @"firstname" and the value would be @"david". That being said, you might consider using a better persistence model like CoreData. You can also use an Sqlite database or have the key/value saved in a plist. There are a number of ways to do this.

For reference ,see this: Save string to the NSUserDefaults?

Community
  • 1
  • 1
Arsalan Habib
  • 1,395
  • 14
  • 20