Reputation: 6662
I have a tableView where I can select a ship from a list, and when I tap it I want the information to pop up on another screen. The way I am currently doing this is:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
cargoShips* ship=[boatsForOwner objectAtIndex:indexPath.row];
UITableViewCell *cell = [self.boatsTableView cellForRowAtIndexPath:indexPath];
[self performSegueWithIdentifier:@"boatInfoSegue" sender:cell];
NSString *nameString = ship.name;
NSString *sizeString = ship.size;
NSUserDefaults *shipName = [NSUserDefaults standardUserDefaults];
[shipName setObject:nameString forKey:@"globalName"];
[shipName synchronize];
NSUserDefaults *shipSize = [NSUserDefaults standardUserDefaults];
[shipSize setObject:sizeString forKey:@"globalSize"];
[shipSize synchronize];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
And to load it back into text (in another file)
NSString *getName = [[NSUserDefaults standardUserDefaults]
objectForKey:@"globalName"];
NSString *getSize = [[NSUserDefaults standardUserDefaults]
objectForKey:@"globalSize"];
shipNameText.text = getName;
shipSizeText.text = getSize;
Now , this works great, except for the fact that it does not return the cell I selected to get to the infoView, but the previous selected object. So if I select the first object on the list, it returns null, the next item i select gets the result I should have had for the first object and so on.
What did I do wrong and how can I fix it?
Upvotes: 1
Views: 118
Reputation: 16674
NSUserDefaults
is tool for saving settings, not for transferring object.
If I were you I made it this way:
#pragma mark - Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue
sender:(id)sender {
if ([segue.identifier isEqualToString:@"boatInfoSegue"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
CargoShip *ship = boatsForOwner[indexPath.row];
BoatViewController *vc = (BoatViewController *)segue.destinationViewController;
vc.ship = ship;
}
}
Class names should be capitalized, that's why I wrote CargoShip
Upvotes: 2
Reputation: 3152
From what I can see in your code. your problem is that you first perform the seque and then update the values in the NSUserDefaults
move this line [self performSegueWithIdentifier:@"boatInfoSegue" sender:cell];
to the end of the method.
This should make it work, but you need to refactor you code.
Upvotes: 0