简体   繁体   中英

Parse JSON to Realm DB efficiently in IOS(Objective-C)

I'm new in Realm and Objective-C. I already have a app that read a JSON array and parse to Realm. Works fine but take 2:30 minutes to parse over 20.000 objects. I need do the parse in less time.

this is my JSON structure:

    {"resultados":[
  {
    "id": 1,
    "tipo": 9,
    "titulo": "name tittle curso",
    "id_padreactividad": 0,
    "hora": "16:55-20:30",
    "fecha": "15/02/2015",
    "acreditado": "Sí",
    "num_creditos": 0.5,
    "ubicacion": 2,
    "tema": "null",
    "patrocinadorId": 0
  },
  {
    "id": 2,
    "tipo": 16,
    "titulo": "Apertura e Introducción\n",
    "id_padreactividad": 1,
    "hora": "16:55-17:00",
    "fecha": "15/02/2015",
    "num_creditos": 0.0,
    "ubicacion": 2,
    "tema": "null",
    "patrocinadorId": 0,
    "descripcion": "null"
  },ect...

And this is my code to parse from JSON to realm

//obtenemos los datos del json con esta simple estructura
    NSData *allCoursesData = [[NSData alloc] initWithContentsOfURL:
                              [NSURL URLWithString:@"String-for-http-direction-to-json"]];

    NSError *error;
    //hacemos el parseo del json, el error está creado por si fallara para que no siga
    NSMutableDictionary *allCourses = [NSJSONSerialization
                                       JSONObjectWithData:allCoursesData
                                       options:NSJSONReadingMutableContainers
                                       error:&error];

    if( error )
    {
        NSLog(@"%@", [error localizedDescription]);
    }
    else {
        NSArray *resultado = allCourses[@"resultados"];
        total=[resultado count];


        for ( NSDictionary *theCourse in resultado )
        {
            // NSLog(@"Insertando actividad...%d",contador);
            NSLog(@"%d/%d",progress,total);
             contador=contador+1;


            Objeto=[[ActividadBean alloc] init];

            Objeto.id_act = [theCourse[@"id"] intValue];
            Objeto.tipo = [theCourse[@"tipo"]intValue];
            Objeto.titulo = theCourse[@"titulo"];
            Objeto.id_padreactividad = [theCourse[@"id_padreactividad"]intValue];
            Objeto.hora = theCourse[@"hora"];
            Objeto.fecha = theCourse[@"fecha"];
            Objeto.acreditado = theCourse[@"acreditado"];
            Objeto.num_creditos = [theCourse[@"num_creditos"] floatValue];
            Objeto.ubicacion = [theCourse[@"ubicacion"] intValue];
            Objeto.tema = theCourse[@"tema"];
            Objeto.patrocinadorId=[theCourse[@"patrocinadorId"]intValue];
            //guardamos el objeto
            [Objeto save];
        }
    }

This work fine, all is import without problem but take several time (2:30 minutes for over 20000 parses) I know that java have the method "createAllFromJson" but I don't know if IOS have something like that.

What portion of your code is spent just building the allCourses dictionary? It's unclear if you're getting the JSON from a local or remote source, so that could be contributing to this length process.

If the JSON deserialization is taking a significant amount of time, you could look into using alternative JSON parsers, or a more efficient data format (like Realm, or BSON).

There's also a call to [Objeto save] in your sample, which I suspect creates a new write transaction for each item in the 20.000 collection, which has significant overhead in Realm. You should instead take advantage of Realm's transactional writing model and write all 20.000 items in a single write transaction, which will speed up the Realm portion of this.


I highly recommend that you use the "Time Profiler" included in Instruments.app to profile where your code is spending most of its time. This will save you time in the future rather than asking on Stack Overflow to get strangers on the Internet to guess where your code might be spending its time ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM