Search code examples
iosobjective-cstatic-data

What is the best way to load static objects in an iOS app?


I have a list of about 100 address. I want to use the CLGeocoder Class and the geocodeAddressDictionary or geocodeAddressString methods to get a list of CLPlacemarks for each address. I don't want the app to do this every time it starts up (as the addresses never change and it requires internet). How can I statically store a list of 100 CLPlacemark objects to be loaded each time the app launches?


Solution

  • I suggest:

    Store the list in your app bundle as a .plist file or a JSON file which can then be parsed on launch into a static NSDictionary or as an instance variable of a Singleton object.

    First serialise your 100 addresses into a JSON file. You can try use some online tools like: http://www.objgen.com/json

    Once you have a text JSON file drag the file into your project in Xcode. You can then parse it using:

    NSError *error;
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Addresses" ofType:@"json"];  
    NSURL *localFileURL = [NSURL fileURLWithPath:filePath];
    NSData *contentOfLocalFile = [NSData dataWithContentsOfURL:localFileURL];
    NSDictionary *addresses = [NSJSONSerialization JSONObjectWithData:contentOfLocalFile 
                                                options: NSJSONReadingMutableContainers 
                                                  error:&error];
    

    You can use same method to deserialise PLIST file.