Три класса зависимости - возвращение данных
Я больше дня думал об одной зависимости, с которой я столкнулся. Я новичок в Objective-C, поэтому, пожалуйста, будьте спокойны со мной. Я даже не знал, как погуглить проблему, с которой я столкнулся.
У меня есть три класса:
RootViewController
HttpRequestWrapper
ManagementClass
куда RootViewController
наследуется ManagementClass
, (@interface RootViewController : ManagementClass <UINavigationControllerDelegate>
).
Так в ManagementClass
Я называю эту функцию:
[[self.navigationController topViewController] getTableData];
где topViewController
это RootViewController
(но позже я хочу изменить его для любого topViewController
в данный момент).
Эта функция getTableData
звонки HttpRequestWrapper
и в этом URLConnection
вызывается со всеми своими делегатами. Но когда дело доходит до метода делегата - (void)connectionDidFinishLoading:(NSURLConnection *)connection
Я хочу с NSNotification
уведомить RootViewController
чтобы загрузка данных из запроса была сделана и заполнить таблицу данными. Но NSNotification
не уведомляет RootViewController
хотя это topViewController
в стеке навигации.
Итак, мой вопрос, как я могу получить данные от URLConnection
к RootViewController
даже если запрос был инициализирован через ManagementClass
в пути.
Вот немного кода моей проблемы:
Класс RootViewController
:
#import "RootViewController.h"
......
// Get the data using the class HttpRequstWrapper (where I wrap the request in NSURLConnection)
- (void) getTableData{
httpRequestWrapper = [HttpRequestWrapper alloc];
[httpRequestWrapper getXMLDataWithURL:[NSString stringWithFormat:@"equipment/xml"]];
}
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// Get Table Data
[self getTableData];
}
- (void) populateTableData{
// Maybe change this line that error is shown if no data is found
if (httpRequestWrapper.dataFromTheHttpRequest == nil){
NSLog(@"Data got from the HttpRequestWrapper is nil or empty");
}
// Parse the returned data
xmlcont = [[XMLController alloc] loadXMLByURL:httpRequestWrapper.dataFromTheHttpRequest];
// Get the names of the Equipments as names of each Section
arrayEquipments = [NSMutableArray alloc];
arrayEquipments = xmlcont.equipments;
sectionsTitles = [[NSMutableArray alloc]init];
for (Equipment *eq in arrayEquipments){
[sectionsTitles addObject: eq.equipmentName];
}
// Reload the data in TableView
[self.tableView reloadData];
}
- (void) viewDidLoad{
....
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(populateTableData) name:@"connectionFinishedLoading" object:nil];
}
Класс ManagementClass
: в.h файле
@interface ManagementClass : UITableViewController {}
в.m файле
@implementation ManagementClass
- (void) refreshPage {
if ([[self.navigationController topViewController] isKindOfClass: [RootViewController class]]){
[[self.navigationController topViewController] getTableData];
}
}
И в HttpRequestWrapper
класс у меня есть:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
......
if ([urlExtension rangeOfString: @"notification"].location != NSNotFound) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"connectionFinishedLoading1" object:nil];
} else if ([urlExtension rangeOfString: @"execution/workflow"].location != NSNotFound) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"connectionFinishedLoadingPhaseView" object:nil]; execution/workflow
} else if ([urlExtension rangeOfString: @"equipment/xml"].location != NSNotFound) {
//[[self.navigationController topViewController] populateTableData]; - not working
[[NSNotificationCenter defaultCenter] postNotificationName:@"connectionFinishedLoading" object:nil];
}
.......
}
Я хочу, чтобы как можно чаще использовать контроллеры. У меня была идея поставить [[self.navigationController topViewController] populateTableData]
в connectionDidFinishLoading
но контроллер навигации не может быть вызван из HttpRequstWrapper
, он просто не выполняется. Я до сих пор не могу понять, почему. Я могу только выполнить navigationController
методы с ViewController
из View
это видно в данный момент.
1 ответ
Из того, что я вижу, вы слушаете "connectionFinishedLoading" в RootViewController и публикуете "connectionFinishedLoading1" в HttpRequestWrapper. Они должны быть одинаковыми, чтобы быть пойманным RootViewController