最有效的方法从数据库创建对象



我是一个程序员新手,所以我很抱歉这个问题的性质。在这种情况下,从外部源加载信息的最快和最有效的方法是什么?是否有比每次通过循环访问dataWithContentsOfURL方法更快的方法?

dispatch_queue_t callerQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_queue_t downloadQueue = dispatch_queue_create("Lots of requests", NULL);
dispatch_async(downloadQueue, ^{
      NSString *stringURL = [NSString stringWithFormat:@"http://livveknowingly.com/dataDraw.php"];
      NSURL *url = [NSURL URLWithString:stringURL];
      NSURLResponse *response;
      NSError *error;
    NSData *data = [NSURLConnection sendSynchronousRequest:[[NSURLRequest alloc]initWithURL:url] returningResponse:&response error:&error];
    _json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
      //NSLog(@"Here is the json %@", _json);
    _beaconsArray = [[NSMutableArray alloc] init];
    BeaconsArray *ba = [BeaconsArray singleton];
    for (int i = 0; i < _json.count; i++) {
                //create object
        NSString *title = [[_json objectAtIndex:i] objectForKey:@"title"];
        NSString *imageName = [[_json objectAtIndex:i] objectForKey:@"image"];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat: @"http://livveknowingly.com/imageUploads/museumTest/%@", imageName]]]];
       // NSData *new = [[NSData alloc] initWithBase64EncodedData:[[_json objectAtIndex:i] objectForKey:@"image"] options:0];
        //UIImage *image = [UIImage imageWithData:new];
        NSString *description = [[_json objectAtIndex:i] objectForKey:@"description"];
        NSString *webLink = [[_json objectAtIndex:i] objectForKey:@"webLink"];
        NSString *questionOne = [[_json objectAtIndex:i] objectForKey:@"questionOne"];
        NSString *questionTwo = [[_json objectAtIndex:i] objectForKey:@"questionTwo"];
        NSString *hintImageOne = [[_json objectAtIndex:i] objectForKey:@"hintImageOne"];
        NSString *hintImageTwo = [[_json objectAtIndex:i] objectForKey:@"hintImageTwo"];
        NSString *supBeaconOne = [[_json objectAtIndex:i] objectForKey:@"supBeaconOne"];
        NSString *supBeaconTwo = [[_json objectAtIndex:i] objectForKey:@"supBeaconTwo"];
        [ba.beaconsArray addObject:[[Exhibit alloc] initWithInfo:title andImage:image andDesc:description andWeb:webLink andQuesOne:questionOne andQuesTwo:questionTwo andHintOne:hintImageOne andHintTwo:hintImageTwo andSubBeaconOne:supBeaconOne andSubBeaconTwo:supBeaconTwo]];
        NSLog(@"hererererererer %@", ba.beaconsArray);
    }
    });
dispatch_async(callerQueue, ^{
        });

你不需要分配所有这些中间变量。

您可以使用文字表示法访问_json的索引及其各自的属性:

Exhibit *e = [Exhibit alloc] initWithInfo:[_json[i][@"title"]]
                                 andImage:[_json[i][@"image"]]
                                  andDesc:[_json[i][@"description"]]
                                          ...
[ba.beaconsArray addObject:e];

最新更新