I am unable to display a NSString into the UILabel. Below is part of the program shown, when the button is hit, those functions will be called.
This is the function that will be called by the UIAlert when the button is hit. It is in the Second View of a Navigation Controller. "location" is a NSString.
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0)
{
NSString *newString = [[NSString alloc] initWithString:location];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:newString forKey:@"keyForLocation"];
FirstViewController *newObject = [[FirstViewController alloc] init];
[newObject updateCurrentLocationLabel:nil];
}
else {
}
}
This is in the header and implementation file of the View Controller of the Base View. Which is with the UILabel.
Header file
@interface FirstViewController : UIViewController {
IBOutlet UILabel *currentLocationLabel;
}
@property (nonatomic, retain) UILabel *currentLocationLabel;
-(IBAction) updateCurrentLocationLabel:(id) sender;
Implementation file
- (IBAction) updateCurrentLocationLabel:(id) sender {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *myString1 = [prefs stringForKey:@"keyForLocation"];
currentLocationLabel.text = [NSString st开发者_如何学PythonringWithFormat:@"%@", myString1];
}
In the alertView:clickedButtonAtIndex:
method, you're creating a new FirstViewController
object that has nothing to do with the one that is (presumably) on your navigation stack.
You have to call the updateCurrentLocationLabel
method on a view controller that is actually part of your view hierarchy. Just because you instantiate the same class doesn't mean you'll get the same object.
You need to call [[NSUserDefaults standardUserDefaults] synchronize]
first. Your defaults are not saved.
精彩评论