2014-03-20 3 views
0

У меня есть ViewController, где я ввожу ключ через текстовое поле. Введенный ключ вытаскивает все доступные записи из базы данных независимо от того, найден ли тот же ключ. Список записей формирует NSMUtableArray, который я передаю в TableViewController, где пользователь может выбрать один. Затем на исходном ViewController это значение должно быть выбрано.Как открыть UITableViewController modally и передать NSMutableArray

два вопроса:

  1. Есть ли способ, чтобы открыть TableViewController как модальный и программно (не с раскадровка)? У меня есть некоторые инструкции «if», которые должны контролировать, открывается ли TableViewController.

  2. Я не могу передать массив из ViewController в TableViewController. Поскольку у меня нет ответа на вопрос 1, я делаю это, используя другую кнопку (тест). NSLog в UITableViewController сообщает мне, что массив имеет значение null.

UIViewController:

// Add a Navigation Point 
-(IBAction) addIcaoNavigation:(id)sender { 

    // Setting up the path to the navigation points database 
    pathNav = [[NSBundle mainBundle] pathForResource:@"navdata_nav" 
               ofType:@"txt"]; 

    // Text entered in the textfield is assigned as the Navigation Point 
    navigationPoint = txtNavIcao.text; 

    // If the Departure airport is not determined, this will give an error. Determine  Departure first. 
    if ([txtDepIcao.text isEqual:@""] || portDeparture == nil) { 
     // Pop-up message that the airport was not found 
     UIAlertView* portNotFoundMsg; 
     portNotFoundMsg = [[UIAlertView alloc] initWithTitle:@"No Departure airport" 
                message:@"Select the Departure airport first" 
                delegate:self 
              cancelButtonTitle:@"OK" 
              otherButtonTitles:nil, nil]; 
     [portNotFoundMsg show]; 
    } 

    else { 

     // Create an object for the Navigation Points 
     IGDNavigation* navObj = [[IGDNavigation alloc] initWithName: navigationPoint navdataPath: pathNav]; 

     // Creating a list of all points with the same code sorted by the distance from departure 
     navigationList = [navObj navDataWithPreviousLatitude:depLatitude PreviousLongitude:depLongitude]; 

     NSLog(@"NAVIGATION LIST: %@", navigationList); // This works, array created 


     // Pass navigation list !!! 
     IGANavListTableViewController *listObj = [[IGANavListTableViewController alloc]init]; 
     [listObj obtainNavList:navigationList]; 

     // Open the UITableViewController 
     // THIS IS WHERE YOUR HELP OF Q1 IS NEEDED. 

UITableViewController:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // Pass the list of Navigation Points 
    IGAViewController *mainObj = [[IGAViewController alloc] init]; 

    NSLog(@"VIEW DID LOAD: %@", listOfNavPoints); // listOfNavPoints is nul. 

    // The following would work though 
    /* 
    listOfNavPoints = [[NSMutableArray alloc] initWithObjects: 
    @"AAAA", 
    @"BBBB", 
    @"CCCCC", 
    nil]; 
    */ 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    //UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 


    // Configure the cell... 
    if (cell==nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
     if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { 
      cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
     } 
    } 

    cell.textLabel.text = [listOfNavPoints objectAtIndex:indexPath.row]; 

    return cell; 
} 


// Created this method just in case, although it should be enough to have a setter. Either do not work. 
-(void) obtainNavList: (NSMutableArray *) navList { 
    listOfNavPoints = navList; 
} 

UPDATE:

Изменен код, но он по-прежнему не работает. Зачем???!!!

- (void)viewDidLoad { 
[super viewDidLoad]; 

// Pass the list of Navigation Points 
IGAViewController *mainObj = [[IGAViewController alloc] init]; 

listOfNavPoints = [[NSMutableArray alloc] init]; 
listOfNavPoints = mainObj.navigationList; 

NSLog(@"VIEW DID LOAD: %@", listOfNavPoints); 
} 


NAVIGATION LIST: (
    "NDB|GIG|GERING|41.944356|-103.683|341 Khz|639 nm", 
    "NDB|GIG|GINGIN|-31.459722|115.865556|372 Khz|8275 nm" 
) 

VIEW DID LOAD null. 
+0

вы просто инициализируете его, передаете значения получения и создаете объекты для отображения // Переходите список навигации !!! IGANavListTableViewController * listObj = [[IGANavListTableViewController alloc] init]; –

+0

Извините. Я не совсем понимаю. Я инициализирую его, а затем перейду в UITableViewController с помощью '[listObj getNavList: navigationList];' Может быть, мне нужно сделать следующее в viewDidLoad: 'listOfNavPoints = mainObj.navigationList'? Я мог бы попробовать, хотя и это не сработало ... Я попробую еще раз –

+0

Изменен код, но он не работает (см. Обновление в исходном сообщении) –

ответ

0

OK. Я решил проблему, передав данные методом prepareForSegue и выполнив segue в IBAction, используя метод performSegueWithIdentifier. Спасибо всем за помощь.

Смежные вопросы