应用程序在解析json时被冻结

时间:2013-11-01 07:17:14

标签: ios json parsing

我在这里使用NSURLConnection delegate解析5个url,它从mysql db&中检索json。在用户登录时将核心数据插入到数据库中。但是代码花费了太多时间,如何减少时间请帮助。

dispatch_queue_t myBackgroundQueue;
myBackgroundQueue = dispatch_queue_create("loginTask", NULL);

dispatch_async(myBackgroundQueue, ^(void){
   // code for parsing 5 urls
  json_parser *obj= [[json_parser alloc]init];
  [obj parseUrl:@"myurl"];
});

@interface json_parser () {   
    NSMutableArray *array;
    NSMutableData *mdata;
    NSURLConnection *conn;
}

@end 

@implementation json_parser

- (void)parseUrl:(NSString *)baseUrl
{
    NSURL *url=[NSURL URLWithString:baseUrl];
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    conn=[NSURLConnection connectionWithRequest:request delegate:self];

    if(conn) {
        mdata=[[NSMutableData alloc]init];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [mdata setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{      
    [mdata appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{        
    NSDictionary *allData=[NSJSONSerialization JSONObjectWithData:mdata options:0 error:nil];

    for (NSDictionary *dict in allData)
    {
        masterGeneric *masterObj=[[masterGeneric alloc]init];//this is nsobject type class
        masterObj.masterId=[dict objectForKey:@"id"];
        masterObj.genericname=[dict objectForKey:@"genericname"];
        masterObj.salient_features=[dict objectForKey:@"salient_features"];
        masterObj.bioactivity_group=[dict objectForKey:@"bioactivity_group"];
        masterObj.therapy_group=[dict objectForKey:@"therapy_group"];
        masterObj.dosage_information=[dict objectForKey:@"dosage_information"];
        masterObj.indications=[dict objectForKey:@"indications"];
        masterObj.food=[dict objectForKey:@"food"];
        masterObj.interaction=[dict objectForKey:@"interaction"];
        masterObj.side_effects=[dict objectForKey:@"side_effects"];
        masterObj.precautions=[dict objectForKey:@"precautions"];
        masterObj.warnings=[dict objectForKey:@"warnings"];
        masterObj.advice_to_patients=[dict objectForKey:@"advice_to_patients"];
        masterObj.route_of_administration=[dict objectForKey:@"route_of_administration"];
        masterObj.available_form=[dict objectForKey:@"available_form"];
    }
}

0 个答案:

没有答案