В моем приложении для iPhone у меня есть кнопка обновления, которая при нажатии добавляет новое подпредставление. Это новое представление покрывает весь экран, а представление таблицы недоступно до тех пор, пока не будет завершено все действие обновления. Это фактически идея, но я возникла следующая проблема с его реализацией - вид отображается слишком медленно, всплывающее окно занимает 2 или 3 секунды.
Я думал, что возможным решением было бы запустить новый поток и синхронизировать его, но я не уверен, поможет ли это вообще.
- (IBAction) updateButtonPressed: (id)sender {
self.updateButton.enabled = NO;
//HERE STARTS THE LOADING VIEW
LoadingView * loadingView =[LoadingView initializeLoadingView:[self.view.window.subviews objectAtIndex:0]];
//HERE STARTS THE LOADING VIEW
[self deleteData];//delete old data
[self insertNewData];
[self loadNewData];
//THE LOADING VIEW IS DISMISSED
[loadingView dismissView];
//THE LOADING VIEW IS DISMISSED
self.updateButton.enabled = YES;
}// updateButtonPressed
Представление должно отображаться сразу после начала действия, потому что в противном случае вся логика программы пойдет в ад.
EDIT:
Вот код для обоих методов: insertNewData и loadNewData
.
- (void) insertNewData
{
NSString *urlStr;
NSError *error;
NSURLResponse *response;
if(self.title == @"New York")
{
urlStr =[[NSString alloc] initWithFormat: @"http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query=New_York,IL"];
}
else
urlStr = [NSString stringWithFormat:@"http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query=%@,IL",self.title];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:urlStr]];
NSData *dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
xmlControl = [[XMLController alloc] loadXMLbyData:dataReply];
Forecast *forecast;
for(ForecastPeriod *newForecast in [xmlControl weatherForecasts])
{
forecast = [[Forecast alloc] initWithEntity:[NSEntityDescription entityForName:@"Forecast" inManagedObjectContext:self.managedObjectContext] insertIntoManagedObjectContext:self.managedObjectContext];
[forecast setValue:newForecast.conditions forKey:@"conditions"];
[forecast setValue:newForecast.day forKey:@"day"];
[forecast setValue:newForecast.icon forKey:@"icon"];
[self addImagesAtSpecificDirectory:newForecast.icon];
[forecast setValue:newForecast.max forKey:@"max"];
[forecast setValue:newForecast.min forKey:@"min"];
[forecast setValue:newForecast.month forKey:@"month"];
[forecast setValue:newForecast.period forKey:@"period"];
[forecast setValue:newForecast.weekday forKey:@"weekday"];
[forecast setValue:newForecast.year forKey:@"year"];
[forecast setValue:self.title forKey:@"location"];
}
if (![self.managedObjectContext save:&error]) {
NSLog(@"Couldn't save: %@", [error localizedDescription]);
}
}//insertNewData
- (void) loadNewData
{
AppDelegate *appDelegate = (AppDelegate*) [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = appDelegate. managedObjectContext;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Forecast" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"period" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"location = %@",self.title];
[request setPredicate:predicate];
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
self.items = mutableFetchResults;
[self.tableView reloadData];
[mutableFetchResults release];
[request release];
//iPad
if ([[UIDevice currentDevice] userInterfaceIdiom]==UIUserInterfaceIdiomPad && popOver_ != nil)
{
[popOver_ dismissPopoverAnimated:YES];
}
}//loadNewData