如何在Objective-C中将反向编码的数据保存到CoreData



我正在尝试对当前位置进行反向地理编码,检索城市和州,并将其保存到CoreData实体中。在下面的代码中,一旦用户点击保存按钮,我就希望进行反向地理编码,并将城市和州信息保存到核心数据中。但当我尝试执行下面的代码时,反向地理编码部分不会执行,也不会将任何数据保存到核心数据中。我在其他线程中发现的一个指针是,反向地理编码发生在一个独立的线程中,该函数的稍后部分在没有进行反向地理编码的情况下启动。有人能指导我如何处理这个问题吗?我还是iOS应用程序开发的新手,所以非常感谢您的详细回复。提前感谢!

- (IBAction)save:(id)sender {
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //Update current location
    [self.locationManager startUpdatingLocation];
    // Reverse Geocoding
    NSLog(@"Resolving the Address");
    [geocoder reverseGeocodeLocation:self.locationManager.location completionHandler:^(NSArray *placemarks, NSError *error)
    {
        NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
        if (error == nil && [placemarks count] > 0) {
            placemark = [placemarks lastObject];
        } else {
            NSLog(@"%@", error.debugDescription);
        }
    } ];
    NSManagedObjectContext *context = [self managedObjectContext];
    // Create a new device
    NSManagedObject *newPlace = [NSEntityDescription insertNewObjectForEntityForName:@"Place" inManagedObjectContext:context];
    [newPlace setValue:placemark.locality forKey:@"city"];
    [newPlace setValue:placemark.administrativeArea forKey:@"state"];
    NSError *error = nil;
    // Save the object to persistent store
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

试试这个:

- (IBAction)save:(id)sender {
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //Update current location
    [self.locationManager startUpdatingLocation];
    // Reverse Geocoding
    NSLog(@"Resolving the Address");
    [geocoder reverseGeocodeLocation:self.locationManager.location completionHandler:^(NSArray *placemarks, NSError *error)
    {
        NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
        if (error == nil && [placemarks count] > 0) {
            placemark = [placemarks lastObject];
            NSManagedObjectContext *context = [self managedObjectContext];
            // Create a new device
            NSManagedObject *newPlace = [NSEntityDescription insertNewObjectForEntityForName:@"Place" inManagedObjectContext:context];
            [newPlace setValue:placemark.locality forKey:@"city"];
            [newPlace setValue:placemark.administrativeArea forKey:@"state"];
            NSError *error = nil;
            // Save the object to persistent store
            if (![context save:&error]) {
                NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            NSLog(@"%@", error.debugDescription);
        }
    }];
}

正如你所看到的,我把保存数据的代码放在反馈回调中。回调是异步的,在信息可用后调用(可能需要时间,例如2秒)。如果您试图在收到数据之前保存数据,那么您将不会存储任何内容。

相关内容

  • 没有找到相关文章

最新更新