Search code examples
iosstoryboardtableviewseguensindexpath

storyboard NSIndexPath


I try use storyboard with table view that segue to controller view that should show me picture. The problem is that the app crush when I press on any "cell".

this is the problem code:

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

    if([[segue identifier] isEqualToString:@"ShowPhoto"])
    {
        DetailsViewController *dvc = [segue 
        destinationViewController];
        NSIndexPath *path = [[self tableView] indexPathsForSelectedRows];
        Photo *pic = [photosArray objectAtIndex:[path row]];

        [dvc setCureentPic: pic];
    }
}

the problem is the line with NSIndexPath... I think that the reason is that I try insert array into NSIndex. xcode warning: Incompatible pointer types initializing 'NSIndexPath *__strong' with an expression of type 'NSArray.

the crush message: unrecognized selector sent to instance [__NSArrayI row]. how can I solve the problem?


Solution

  • Please do read the documentation (here) of the methods you call instead of making assumptions about what they do...

    [[self tableView] indexPathsForSelectedRows]
    

    returns an NSArray and not an NSIndexPath (by the way, you could know this even without reading the docs - in Cocoa naming convention, if something is in plural, then it accepts or returns an NSArray), so sending it the messages of NSIndexPath will crash. Write

    NSIndexPath *path = [[[self tableView] indexPathsForSelectedRows] objectAtIndex:0];
    

    instead, and it will work (if there is at least one selected row - if not, you have to check for the array being empty, else it will crash again...)

    By the way, the compiler even warns you about what the problem is... Please try to develop some common sense before trying to do programming, because if not, you will shoot yourself and others in the foot.