Pergunta

I've been struggling with this for ages now and I really need some good help here. :) I have an app where I'm parsing a quite big JSON into appdelegate's didFinishLaunchingWithOptions.

My Model Objects are:

Tab:

NSString *title
NSMutableArray *categories

Category:

NSString *title
NSMutableArray *items

Item

NSString *title
NSString *description
UIImage *image

I need to save the data locally, cause the parsing takes about 15 seconds every time my app starts. I'm using the SBJSON framework.

Here's my code for parsing:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"json_template" ofType:@"json"];

    NSString *contents = [NSString stringWithContentsOfFile: filePath  encoding: NSUTF8StringEncoding error: nil];
    SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
    NSMutableDictionary *json = [jsonParser objectWithString: contents];
    tabs = [[NSMutableArray alloc] init];
    jsonParser = nil;

    for (NSString *tab in json)
    {
        Tab *tabObj = [[Tab alloc] init];
        tabObj.title = tab;

        NSDictionary *categoryDict = [[json valueForKey: tabObj.title] objectAtIndex: 0];
        for (NSString *key in categoryDict)
        {

            Category *catObj = [[Category alloc] init];
            catObj.name = key;


            NSArray *items = [categoryDict objectForKey:key];

            for (NSDictionary *dict in items)
            {
                Item *item = [[Item alloc] init];
                item.title = [dict objectForKey: @"title"];
                item.desc = [dict objectForKey: @"description"];
                item.url = [dict objectForKey: @"url"];
                if([dict objectForKey: @"image"] != [NSNull null])
                {
                    NSURL *imgUrl = [NSURL URLWithString: [dict objectForKey: @"image"]];
                    NSData *imageData = [NSData dataWithContentsOfURL: imgUrl];
                    item.image = [UIImage imageWithData: imageData];
                }
                else
                {
                    UIImage *image = [UIImage imageNamed: @"standard.png"];
                    item.image = image;
                }

                [catObj.items addObject: item];   
            } 
            [tabObj.categories addObject: catObj];
        } 
        [tabs addObject: tabObj];
    }

What is the best way of doing this? Using Core Data or NSFileManager? If you have som code example too it will make me very happy. This is the last thing i need to fix before the app is ready for app store and it just kills me! I can't solve this problem.

Foi útil?

Solução

If you are working on iOS then you save a file to the Documents folder. On Mac OS X it would be in the Application Support folder. Since you are on iOS, read this answer for how to access the Documents folder.

All of the objects that you want to store should implement NSCoding. The above variables already do. Should you want to store the tabs, categories and items directly they would need to implement NSCoding. Then all you need is to serialize them to a file. When opening you app you can look for this file and get your objects back without parsing.

The code should look something like this (untested and error checking is ommited for brevity):

- (void) saveStateToDocumentNamed:(NSString*)docName
{
    NSError       *error;
    NSFileManager *fileMan = [NSFileManager defaultManager];
    NSArray       *paths   = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString      *docPath = [paths[0] stringByAppendingPathComponent:docName];

    if ([fileMan fileExistsAtPath:docPath])
        [fileMan removeItemAtPath:docPath error:&error];

    // Create the dictionary with all the stuff you want to store locally
    NSDictionary *state = @{ ... };

    // There are many ways to write the state to a file. This is the simplest
    // but lacks error checking and recovery options.
    [NSKeyedArchiver archiveRootObject:state toFile:docPath];
}

- (NSDictionary*) stateFromDocumentNamed:(NSString*)docName
{
    NSError       *error;
    NSFileManager *fileMan = [NSFileManager defaultManager];
    NSArray       *paths   = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString      *docPath = [paths[0] stringByAppendingPathComponent:docName];

    if ([fileMan fileExistsAtPath:docPath])
        return [NSKeyedUnarchiver unarchiveObjectWithFile:docPath];

    return nil;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top