2012-04-12 140 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。

你看,最需要什麼時間和更新帖子。或者,也許你可以自己解決它)