Luke Irvin Luke Irvin - 7 days ago 6
iOS Question

Issue with NSUserDefaults

In ViewController A:

// ViewDidLoad

self.theArray = // set up my array here with objects

// TableView

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.viewControllerTwo = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];

self.myString = [self.theArray objectAtIndex:indexPath.row];

[[NSUserDefaults standardUserDefaults] setValue:self.myString forKey:@"stringKey"];
[[NSUserDefaults standardUserDefaults] synchronize];

[self.navigationController pushViewController:self.viewControllerTwo animated:YES];
}


In ViewController B:

// ViewDidLoad

self.aLabel.text = [[NSUserDefaults standardUserDefaults] stringForKey:@"stringKey"];


In my View Controller A, where I am setting the string in
NSUserDefaults
, I can see that it is matching with the cell I tap on, but when I push to View Controller B, my label is not picking up what is stored in
NSUserDefaults
.

What am I missing?

EDIT:

I changed it to this:

// In FirstViewController

self.viewControllerTwo = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];

self.myString = [self.theArray objectAtIndex:indexPath.row];

self.viewControllerTwo.secondString = self.myString;

[self.navigationController pushViewController:self.viewControllerTwo animated:YES];

// In SecondViewController

self.aLabel.text = self.secondString;

Answer

1、Make sure the string is valid which means it is neither @"" nor "white characters".

2、Make sure the self.aLabel is added to your base view and self.aLabel is not nil.