NSManagedContext 需要很长时间才能持久化



我的应用程序有一个UITableViewController,其中包含表示城市名称的单元格列表。当用户单击单元格时,应用程序会将单元格附件类型更改为 UITableViewCellAccessoryCheckmark,并将单元格的文本值(城市名称)保存到持久存储中。但是,我发现每次单击该单元格时,至少需要 10 秒才能将数据实际存储到持久存储中。知道为什么会这样吗?而不是立即保存数据,为什么需要这么长时间才能持久保存?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cityName = [self.citySettingModel nameOfCityAtIndex:indexPath.row OfCountryAtIndex:self.countryIndex];    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [[self.citySettingModel worldbikesCoreService] removeCity:cityName];
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [[self.citySettingModel worldbikesCoreService] addCity:cityName toCountry:self.countryName];
    }
}

用于创建城市和国家/地区对象的代码位于不同的类中

- (City *) addCity:(NSString*) cityName toCountry:(NSString*) countryName 
{
    NSManagedObjectContext *context = [self.delegate managedObjectContext];
    Country *country = [self.countryDAO addCountry:countryName inManagedObjectContext:context];
    City *city = [self.cityDAO addCity:cityName inManagedObjectContext:context];
    [country addCitiesObject:city];
    return city;
}
- (City*) addCity:(NSString*) cityName inManagedObjectContext:(NSManagedObjectContext *)context
{
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"City"];
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"cityName = %@", cityName];
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"cityName" ascending:YES];
    fetchRequest.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    NSError *error;
    NSArray *matches = [context executeFetchRequest:fetchRequest error:&error];
    if (error) NSLog(@"error when retrieving city entities %@", error);
    City *city;
    if (!matches || [matches count] > 1) ;
    else if ([matches count] == 0) {
        city = [NSEntityDescription insertNewObjectForEntityForName:@"City" inManagedObjectContext:context];
        city.cityName = cityName;
    }
    else city = [matches lastObject];
    return city;
}

找出Xcode中花费如此长时间的真正好方法是Time Profiler - 它应该是您在iOS应用程序开发中最好的朋友。

在 Xcode 中,您应该点击"测试",而不是"运行",而是选择时间分析器。您可以看到任何进程需要多少时间。

还有一些工具可让您检查核心数据提取。

看,什么花了最多的时间并更新帖子。或者,也许,你可以自己解决它)

最新更新