My application has a UITableViewController which has a list of cells representing names of cities. When a user clicks a cell, the application will change the cell accessoryType to UITableViewCellAccessoryCheckmark and save the text value of the cell (city name) into the persisted store. However, I found that every time I click the cell, it requires at least 10 seconds to actually store the data into the Persistent Store. Any idea why this happens? Instead of saving the data immediately, why it takes so long to persist?
- (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];
}
}
The code for create a City and Country objects are in a different class
- (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;
}
The really good way to find out what’s taking so long time in Xcode is Time Profiler – it should be your best friend in iOS app developing.
In Xcode, instead of Run you should hit Test, there select Time Profiler.You can see how much time doe any process takes.
There are also some tools that let you examine Core Data Fetches.
Look, what’s taking most time there and update the post. Or, maybe, you couls solve it by yourself then)