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

时间:2012-04-12 22:07:23

标签: ios cocoa core-data

我的应用程序有一个UITableViewController,它有一个表示城市名称的单元格列表。当用户单击一个单元格时,应用程序会将单元的accessoryType更改为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;
}

1 个答案:

答案 0 :(得分:1)

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

在Xcode中,您应该选择Time Profiler而不是Run,而不是Run,您可以看到任何过程需要多长时间。

还有一些工具可以让您检查Core Data Fetches。

看,那里花了大部分时间并更新帖子。或者,也许,你可以自己解决它然后)