2012-04-12 143 views
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; 
} 
+0

第一:你实际上在上面的代码中保存了上下文吗?我在这里看不到任何储蓄。第二:你不认为你的fetchrequest在addCity中:......可能对这10秒钟负责......? – codeclash 2012-04-14 01:12:22

回答

1

找出什么要花这么长的时间在Xcode真正的好方法的代码是时间探查器 - 它应该是你的在iOS应用开发中最好的朋友。

在Xcode中,而不是Run,您应该点击Test,在那里选择Time Profiler.您可以看到有多少时间是由任何进程完成的。

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

你看,最需要什么时间和更新帖子。或者,也许你可以自己解决它)