Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make variable available to entire application using AppDelegate

I am extraordinarily confused by the concept of using the app delegate to make a variable be able to be set and used anywhere in my application. Here's my code:

appdelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    NSMutableString *globalUsername;
}
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, retain) NSMutableString *globalUsername;

appdelegate.m

@synthesize globalUsername;

and another view scene (called "Forum.h" where I am trying to set the value)

AppDelegate *appDelegate = (MyAppDelegate *)[[[UIApplication sharedApplication] delegate]];
[appDelegate globalUsername appendString;

the last line is incomplete of course, but xcode automatically pickets up globalUsername variable, I just cannot call the "appendString" function to actually change it.

like image 651
mandy b Avatar asked Nov 29 '22 16:11

mandy b


2 Answers

Erm, if you're trying to store a username, why not just use NSUserDefaults ?

// set the username
[[NSUserDefaults standardUserDefaults] setValue:@"johnsmith" forKey:@"username"];
[[NSUserDefaults standardUserDefaults] synchronize];

// retrieve the user name
NSString *username = [[NSUserDefaults standardUserDefaults] valueForKey:@"username"];
like image 70
Zhang Avatar answered Dec 01 '22 05:12

Zhang


You are missing one set of [], those are actually two statements in one. first the method globalUsername is called on appDelegate and the result of that is then send the message appendString (which is missing parameters)

So this should look like this instead:

[[appDelegate globalUsername] appendString:@"foobar"];

But for a game you should not abuse the app delegate like this. Rather I recommend that if you want a global place to store game state you should look into having a Singleton, like I described here: http://www.cocoanetics.com/2009/05/the-death-of-global-variables/

PS: you probably don't want to work with a mutable string there because of several reasons. Better to have the property/ivar a normal NSString and then just set it. I don't see any good reason why you would want to append characters to a user's name. Even though NSStrings are immutable you can simply replace them with other ones.

[[appDelegate setGlobalUsername:@"foobar"];

or with same effect:

appDelegate.globalUsername = @"foobar";
like image 31
Cocoanetics Avatar answered Dec 01 '22 07:12

Cocoanetics