samedi 25 avril 2015

UITableView Navigation not working


I have the following hierarchy in my app but the navigation controller isn't working. When I go back up the hierarchy in the storyboard, the higher level tableview controllers are blank instead of showing the previous view.

UITabBarController
        UINavigationController
                UITableViewController
                UITableViewController
                DetailViewController

Here's my code for the TableView Controller

@interface ExerciseTableViewController ()

@end

@implementation ExerciseTableViewController


- (void)viewDidLoad {

    UIBarButtonItem *add = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addExercise:)];
    self.navigationItem.rightBarButtonItem = add;

    NSLog(@"level: %i, currentSMID: %i, currentMID: %i", _level, _currentSMID, _currentMID);

    if (self.managedObjectContext_ == nil) {
        self.managedObjectContext_ = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    }

    if (_level == 1) {
        _submuscleNameArray = [self submuscleGroup:_currentMID valueForKeyPath:@"submuscleGroup"];
        _submuscleIDArray = [self submuscleGroup:_currentMID valueForKeyPath:@"submuscleID"];
    } else if (_level == 2) {
        //loading and sorting exercise list
        _exerciseList = [self loadExercise:_currentMID sub:_currentSMID];
        _exerciseListSorted = [self sortKeysByName];
    } else {
        [self loadMuscleGroup];
    }

    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    NSInteger count;

    if (_level == 0) {
        count = [_muscleNameArray count];
    } else if (_level == 1) {
        count = [_submuscleNameArray count];
    } else {
        count = [_exerciseList count];
    }

    return count;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_level == 0) {
        int muscleID = [_muscleIDArray[indexPath.row] intValue];
        NSLog(@"MuscleID: %i", muscleID);
        NSArray *submuscleArray = [self submuscleGroup:muscleID valueForKeyPath:@"submuscleID"];
        if (submuscleArray == nil || [submuscleArray count] == 0) {

            _currentMID = muscleID;
            _level = 2;
            _detailTitle = _muscleNameArray[indexPath.row];
                    NSLog(@"title: %@", _detailTitle);
            [self performSegueWithIdentifier:@"drillDown2" sender:self];
        } else {
            _currentMID = muscleID;
            _level = 1;
            _detailTitle = _muscleNameArray[indexPath.row];
                    NSLog(@"title: %@", _detailTitle);
        [self performSegueWithIdentifier:@"drillDown" sender:self];
        }

    } else if (_level == 1) {

        _level = 2;
        _currentSMID = [_submuscleIDArray[indexPath.row] intValue];
        _detailTitle = _submuscleNameArray[indexPath.row];
        [self performSegueWithIdentifier:@"drillDown2" sender:self];

    } else {
        _detailTitle = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:0];
        _equipment = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:1];
        _image = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:2];
        _imageNumber =  [[[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:3] intValue];
        _levelString = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:4];
        _status = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:5];
        _thumbnail = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:6];
        _type = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:7];
        _unitOfMeasure = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:8];
        _video = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:9];
        _workoutDirections = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:10];
        _exerciseID = [[_exerciseListSorted objectAtIndex:indexPath.row] intValue];

        [self performSegueWithIdentifier:@"showExerciseDetail" sender:self];

    }


}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}


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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    if (_level == 0) {
        [[cell textLabel] setText:[_muscleNameArray objectAtIndex:indexPath.row]];
    } else if (_level == 1) {
        [[cell textLabel] setText:[_submuscleNameArray objectAtIndex:indexPath.row]];
    } else {
        [[cell textLabel] setText:[[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:0]];
    }

    return cell;

}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    return nil;
}


#pragma mark - 
#pragma Data Retrieval methods

-(NSArray *) sortKeysByName{

    //Method of NSDictionary class which sorts the keys using the logic given by the comparator block
    NSArray * sortArray = [_exerciseList keysSortedByValueUsingComparator: ^(id obj1, id obj2) {

        //We do case insensitive comparision of two strings as we are not really concerned about
        //the "content" of the strings (please see sortKeysOnTheBasisOfNationalIncome method where
        //we would like to do the comparision with numeric search as an extra option)
        NSComparisonResult result = [[obj1 objectAtIndex:0] caseInsensitiveCompare:[obj2 objectAtIndex:0]];
        return result;
    }];

    //Show Result in the Output Panel
    for (int i = 0; i < [sortArray count]; i++) {
        NSLog(@"WorkoutID:%@, WorkoutName:%@",[sortArray objectAtIndex:i], [[_exerciseList valueForKey:[sortArray objectAtIndex:i]] objectAtIndex:0]);
    }

    return sortArray;
}

- (void)loadMuscleGroup{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    //this is needed because QuizViewController isn't the first level view. The managedObjectContext was nil before this declaration
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Muscle_Group"
                                              inManagedObjectContext:_managedObjectContext_];
    [request setEntity:entity];
    NSError *error;
    _muscleArray = [[_managedObjectContext_ executeFetchRequest:request error:&error] mutableCopy];
    NSSortDescriptor *muscleSort = [[NSSortDescriptor alloc] initWithKey:@"muscleGroup" ascending:YES];
    [_muscleArray sortUsingDescriptors:[NSMutableArray arrayWithObject:muscleSort]];
    _muscleNameArray = [_muscleArray valueForKeyPath:@"muscleGroup"];
    _muscleIDArray = [_muscleArray valueForKeyPath:@"muscleID"];
//    NSLog(@"muscleIDArray count:%i, muscleNameArray count:%i, muscleID1: %d, muscleID2: %d", [_muscleIDArray count], [_muscleNameArray count], _muscleIDArray[1], _muscleIDArray[2]);
}

- (NSArray *)submuscleGroup:(int)muscleID valueForKeyPath:(NSString *)string{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    //this is needed because QuizViewController isn't the first level view. The managedObjectContext was nil before this declaration
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"SubMuscle_Group"
                                              inManagedObjectContext:_managedObjectContext_];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"muscleID = %i", muscleID];
    NSLog(@"muscleID = %i", muscleID);
    [request setPredicate:predicate];
    [request setEntity:entity];
    NSError *error;
    NSMutableArray *submuscleArray = [[_managedObjectContext_ executeFetchRequest:request error:&error] mutableCopy];
    NSSortDescriptor *submuscleSort = [[NSSortDescriptor alloc] initWithKey:@"submuscleGroup" ascending:YES];
    [submuscleArray sortUsingDescriptors:[NSMutableArray arrayWithObject:submuscleSort]];
    NSArray *submuscleGroupArray = [submuscleArray valueForKeyPath:string];
    return submuscleGroupArray;
}

- (NSMutableDictionary *)loadExercise:(int)muscleID sub:(int)subMuscleID{

    //Getting Array from Workout Muscle Relationship Table
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Workout_Muscle_Relationship"
                                              inManagedObjectContext:_managedObjectContext_];
    NSPredicate *predicate;
    if (subMuscleID != 0) {
        predicate = [NSPredicate predicateWithFormat:@"muscleID = %i AND submuscleID = %i", muscleID, subMuscleID];
    } else {
        predicate = [NSPredicate predicateWithFormat:@"muscleID = %i", muscleID];
    }

    [request setPredicate:predicate];
    [request setEntity:entity];
    NSError *error;
    NSMutableArray *workoutRelationshipArray = [[_managedObjectContext_ executeFetchRequest:request error:&error] mutableCopy];
    NSSortDescriptor *workoutSort = [[NSSortDescriptor alloc] initWithKey:@"workoutID" ascending:YES];
    [workoutRelationshipArray sortUsingDescriptors:[NSMutableArray arrayWithObject:workoutSort]];
    NSArray *workoutIDArray = [workoutRelationshipArray valueForKeyPath:@"workoutID"];


    //Getting Array from Workout Group Table
    NSFetchRequest *request2 = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity2 = [NSEntityDescription entityForName:@"Workout_Group_Table"
                                               inManagedObjectContext:_managedObjectContext_];
    [request2 setEntity:entity2];
    NSMutableArray *workoutArray = [[_managedObjectContext_ executeFetchRequest:request2 error:&error] mutableCopy];
    NSSortDescriptor *workoutSort2 = [[NSSortDescriptor alloc] initWithKey:@"workoutID" ascending:YES];
    [workoutArray sortUsingDescriptors:[NSMutableArray arrayWithObject:workoutSort2]];
    NSArray *workoutIDArray2 = [workoutArray valueForKeyPath:@"workoutID"];
    NSArray *workoutName = [workoutArray valueForKeyPath:@"workoutName"];
    NSArray *equipmentArray = [workoutArray valueForKeyPath:@"equipment"];
    NSArray *imageArray = [workoutArray valueForKeyPath:@"image"];
    NSArray *imageNumberArray = [workoutArray valueForKeyPath:@"imageNumber"];
    NSArray *levelStringArray = [workoutArray valueForKeyPath:@"level"];
    NSArray *statusArray = [workoutArray valueForKeyPath:@"status"];
    NSArray *thumbnailArray = [workoutArray valueForKeyPath:@"thumbnail"];
    NSArray *typeArray = [workoutArray valueForKeyPath:@"type"];
    NSArray *unitOfMeasureArray = [workoutArray valueForKeyPath:@"unitOfMeasure"];
    NSArray *videoArray = [workoutArray valueForKeyPath:@"video"];
    NSArray *workoutDirectionsArray = [workoutArray valueForKeyPath:@"workoutDirections"];
    NSArray *workoutID = [workoutArray valueForKeyPath:@"workoutID"];
    NSArray *muscleImageArray = [workoutArray valueForKey:@"muscleImage"];

    NSMutableDictionary *list = [NSMutableDictionary new];

    NSLog(@"workoutIDArray count: %i, workoutIDArray2 count: %i", [workoutIDArray count], [workoutIDArray2 count]);
    int start = 0;

    for (int i = 0; i < [workoutIDArray count]; i ++) {
        NSLog(@"i:%i", i);
        for (int j = start; j < [workoutIDArray2 count]; j++) {
            NSLog(@"j:%i",j);
            if (workoutIDArray[i] == workoutIDArray2[j]) {
                NSArray *temp = [NSArray arrayWithObjects:workoutName[j], equipmentArray[j], imageArray[j], imageNumberArray[j], levelStringArray[j], statusArray[j], thumbnailArray[j], typeArray[j], unitOfMeasureArray[j], videoArray[j], workoutDirectionsArray[j], workoutID[j], muscleImageArray[j], nil];
                NSString *temp2 = [[NSString alloc] initWithFormat:@"%@", workoutIDArray2[j]];
                [list setValue:temp forKey:temp2];
                start = j;
                break;
            }
        }
    }



    return list;

}

- (NSString *)getExerciseInfo:(int)eid valueForKeyPah:(NSString *)string{
    NSString *result;



    return result;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{


    if ([segue.identifier isEqualToString:@"showExerciseDetail"]) {
        //ExerciseDetail *exerciseDetail = (ExerciseDetail *)segue.destinationViewController;
        //exerciseDetail.pageTitle = detailTitle;
        //UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
        ExerciseDetail *exerciseDetail = (ExerciseDetail *)segue.destinationViewController;
        exerciseDetail.title = _detailTitle;
        exerciseDetail.exerciseID = _exerciseID;
        exerciseDetail.imageNumber = _imageNumber;
        exerciseDetail.image = _image;
        exerciseDetail.equipment = _equipment;
        exerciseDetail.levelString = _levelString;
        exerciseDetail.status = _status;
        exerciseDetail.thumbnail = _thumbnail;
        exerciseDetail.type = _type;
        exerciseDetail.unitOfMeasure = _unitOfMeasure;
        exerciseDetail.video = _video;
        exerciseDetail.workoutDirections = _workoutDirections;
    } else if ([segue.identifier isEqualToString:@"drillDown"] || [segue.identifier isEqualToString:@"drillDown2"]){
        //UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
        ExerciseTableViewController *tableView = segue.destinationViewController;
        tableView.title = _detailTitle;
        NSLog(@"title: %@", _detailTitle);
        tableView.delegate = self;
        tableView.level = _level;
        tableView.currentSMID = _currentSMID;
        tableView.currentMID = _currentMID;
        tableView.muscleNameArray = _muscleNameArray;
        if (_level == 2) {
            tableView.submuscleNameArray = _submuscleNameArray;
        }
        NSLog(@"level: %i, currentSMID: %i, currentMID: %i", _level, _currentSMID, _currentMID);
    } else if ([segue.identifier isEqualToString:@"addExercise"]){
        UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
        AddExerciseViewController *addExercise = (AddExerciseViewController *)navController.topViewController;
        addExercise.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;    
    } else if ([segue.identifier isEqualToString:@"dismissView"]){
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)addExercise:(id)sender {
    [self performSegueWithIdentifier:@"addExercise" sender:sender];
}

- (void)viewDidAppear:(BOOL)animated{
    NSLog(@"muscleNameArray count: %i, submuscleNameArray count: %i, exercistList count: %i", [_muscleNameArray count], [_submuscleNameArray count], [_exerciseList count]);
    [super viewDidAppear:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [self.myWorkoutList reloadData];
    NSLog(@"muscleNameArray count: %i, submuscleNameArray count: %i, exercistList count: %i", [_muscleNameArray count], [_submuscleNameArray count], [_exerciseList count]);
    [super viewWillAppear:YES];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


Aucun commentaire:

Enregistrer un commentaire