0
我的應用程序有一個UITableViewController,它有一個表示城市名稱的單元格列表。當用戶單擊一個單元格時,應用程序會將單元格accessoryType更改爲UITableViewCellAccessoryCheckmark,並將單元格(城市名稱)的文本值保存到持久存儲區中。但是,我發現每次單擊單元格時,都需要至少10秒才能將數據實際存儲到持久存儲區中。任何想法爲什麼發生這種情況而不是立即保存數據,爲什麼需要很長時間才能堅持下去?NSManagedContext需要很長時間來堅持
- (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;
}
第一:你實際上在上面的代碼中保存了上下文嗎?我在這裏看不到任何儲蓄。第二:你不認爲你的fetchrequest在addCity中:......可能對這10秒鐘負責......? – codeclash 2012-04-14 01:12:22