Search code examples
iosobjective-cuitableviewseguensnumber

Why NSNumber become zero from one function to another function?


I know this question is very basic but as a java programmer I am confused why this value is becoming zero? I have UITableView and I am trying to send the selected row number to destination UIViewController. However, this is before even sending this value it becomes zero in prepareForSegue

NSNumber* val;
/*segue*/
    - (void)tableView:(UITableView *)tableView
    didSelectRowAtIndexPath:(NSIndexPath*)indexPath {

        //Perform a segue.
        [self performSegueWithIdentifier:@"toInfo"
                                  sender:[items objectAtIndex:indexPath.row]];

        val = [[NSNumber alloc] init];

        val = [NSNumber numberWithInt:indexPath.row];

        NSLog(@"val111 === %@",val);  >>>Here prints 2
    }


    - (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
    //    [self performSegueWithIdentifier:@"toInfo" sender:sender];
        NSLog(@"inside segue");
        NSLog(@"val222 === %@",val);  >>> Here prints null




      InfoViewController *vc = [segue destinationViewController];
        vc.journeyId = val;

     }

Solution

  • It's because you're calling performSegueWithIdentifier:sender: (which in turn calls prepareForSegue:sender: before you've initialized val, so just as in Java, val's going to be nil at that point. Just move your performSegueWithIdentifier:sender: call to the end of tableView:didSelectRowAtIndexPath--or better yet, get rid of tableView:didSelectRowAtIndexPath and instead just create a segue from the table row to the destination view controller.

    Moreover, you don't need the val = [[NSNumber alloc] init]; line, because the following line creates and returns the NSNumber instance.