So I am trying to pass a url between views. I was thinking that the following code will stomp on whatever is in @”url” every time the user makes a selection from the tableview. What actually happens is that the first selection is always being returned and is never stomped on. Hmmmm, maybe it is me? Any ideas? Thanks.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0)
{
[self saveToUserDefaults:@"http://url1"];
[self.navigationController pushViewController:self.webController animated:YES];
}
else if (indexPath.row == 1)
{
[self saveToUserDefaults:@"http://url2"];
[self.navigationController pushViewController:self.webController animated:YES];
}
}
-(void)saveToUserDefaults:(NSString*)myString
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults)
{
[standardUserDefaults setObject:myString forKey:@"url"];
[standardUserDefaults synchronize];
}
}
On the receiving end:
-(NSString*)retrieveFromUserDefaults
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *val = nil;
if (standardUserDefaults)
val = [standardUserDefaults objectForKey:@"url"];
return val;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSString *url = self.retrieveFromUserDefaults;
[self handleURLRequest:url];
}
viewDidLoadis only called when your view is initially loaded from the xib file. If you pop and re-push the view controller then the method won’t be executed again unless you’ve received low memory warnings.Move the code to
viewWillAppearwhich is guarantee to be called every time your view, well, appears.