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.
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"];
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With