So I’d like to access and display a formatted date outside my function. For the date format I am using NSDateFormatter which works fine..
My function (didFinishUpdatesSuccessfully) performs some action and if successful displays an UIAlertView which includes the formatted date. All that works fine..
- (void) didFinishUpdatesSuccessfully {
//--- Create formatted date
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd/MM/YYYY - hh:mm:ss a"];
NSString *dateString = [dateFormatter stringFromDate:currDate]; // dateString contains the current date as a string
[dateFormatter release];
//--- UIAlertView
NSString *title = @"The update has been performed!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: title
message: dateString
delegate: nil
cancelButtonTitle: [FileUtils appResourceForKey:@"UPDATE_GENERAL_BUTTON_TITLE_OK"]
otherButtonTitles: nil];
[alert show];
[alert release];
//--- create new string
// NSMutableString* lastUpdated = [NSMutableString stringWithFormat:@"%@",dateString];
}
I now want to write the value of dateString into a global NSString or NSMutableString and access it somewhere else in the code, e.g. another function etc..
I thought about creating a NSMutableString like this:
NSMutableString* lastUpdated = [NSMutableString stringWithFormat:@"%@",dateString]; and to access lastUpdated somewhere else, but ouside of this function lastUpdated is empty… Can you help? Cheers
If you do that, you’re declaring a local variable named
lastUpdated. Even if there’s another global variable with the same name, this local one will hide the global variable for as long as it’s in scope (the life of your function).To make this work, you need to declare a global
lastUpdatedsomewhere outside of any function or method, probably near the top of a .m file:You can then access that variable from anywhere in the .m file. If you want to access it in other .m files, you’ll want to add an extern declaration in the corresponding header (.h) file:
With that declaration, you can use
lastUpdatedin any file that includes that header file.Two things to know:
This is basic C stuff, so if it seems unfamiliar, you should review scope rules for C. Know the difference between a global variable, a static variable, a local variable, an instance variable (okay, plain old C doesn’t have those), and a parameter.
Global variables are horrible. Don’t trust anybody who tells you otherwise. I offer the advice above to help solve your immediate problem, but a better solution would be to figure out how to refactor your code so that you can avoid the need for a global variable. (And IMO a singleton isn’t the answer, either. Singletons used just to access global data aren’t much more than fancy-pants global variables.)