简体   繁体   English

在 IOS 中高效地将 JSON 解析为 Realm DB(Objective-C)

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

I'm new in Realm and Objective-C.我是 Realm 和 Objective-C 的新手。 I already have a app that read a JSON array and parse to Realm.我已经有一个应用程序可以读取 JSON 数组并解析为 Realm。 Works fine but take 2:30 minutes to parse over 20.000 objects.工作正常,但需要 2:30 分钟来解析超过 20.000 个对象。 I need do the parse in less time.我需要在更短的时间内进行解析。

this is my JSON structure:这是我的 JSON 结构:

    {"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这是我从 JSON 解析到领域的代码

//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.这个工作正常,所有导入都没有问题,但需要一些时间(超过 20000 次解析需要 2:30 分钟)我知道 java 有方法“createAllFromJson”,但我不知道 IOS 是否有类似的东西。

What portion of your code is spent just building the allCourses dictionary?您的代码的哪一部分仅用于构建allCourses字典? It's unclear if you're getting the JSON from a local or remote source, so that could be contributing to this length process.目前尚不清楚您是从本地还是远程源获取 JSON,因此这可能会导致这个长度过程。

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).如果 JSON 反序列化花费大量时间,您可以考虑使用替代 JSON 解析器,或更高效的数据格式(如 Realm 或 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.在您的示例中还有一个对[Objeto save]的调用,我怀疑它会为 20.000 集合中的每个项目创建一个新的写入事务,这在 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.相反,您应该利用 Realm 的事务写入模型并在单个写入事务中写入所有 20.000 个项目,这将加快 Realm 部分的速度。


I highly recommend that you use the "Time Profiler" included in Instruments.app to profile where your code is spending most of its time.我强烈建议您使用 Instruments.app 中包含的“时间分析器”来分析您的代码花费大部分时间的位置。 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 ;)这将在未来节省您的时间,而不是要求 Stack Overflow 上让陌生人在互联网上猜测您的代码可能会在哪里花费时间;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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