0

I would like to pass a string to all my other view controllers from the AppDelegate. I have defined a variable called appName and assign it a string

AppDelegate.h

#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) NSString *appName;

@end

AppDelegate.m

@implementation AppDelegate
@synthesize appName;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    appName=@"SatKacPara";
    return YES;
}

The following implementation does not have access to appName property. I could not able to figure out.

ViewController1.m

appLabel.text=[(AppDelegate*) [UIApplication shareApplication].delegate ].appName;

enter image description here

casillas
  • 16,351
  • 19
  • 115
  • 215
  • 1
    Why not put it in a constants file then? It isn't appropriate to be in the app delegate... – Wain Oct 31 '15 at 22:12
  • 2
    `((AppDelegate*) [UIApplication sharedApplication].delegate).appName`!? – luk2302 Oct 31 '15 at 22:13
  • 1
    You mean the [sharedApplication function](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIApplication_Class/#//apple_ref/occ/clm/UIApplication/sharedApplication) right? It seems you have a typo. – vrwim Oct 31 '15 at 22:14
  • 1
    Why add a property for the app name? You can easily get the app's display name directly from the Info.plist. Use the `infoDictionary` property of `NSBundle`. Use the `CFBundleDisplayName` key. With this you don't need to update any code if you change the app's name or localize it. – rmaddy Oct 31 '15 at 22:19
  • 1
    Duplicate of http://stackoverflow.com/questions/5175878/iphone-access-a-property-value-from-appdelegate?rq=1 – Soberman Oct 31 '15 at 22:46
  • FYI - there is no need for the `@synthesize` line. That's quite outdated in most cases. – rmaddy Oct 31 '15 at 22:55

1 Answers1

3

You have a simple typo in your line of code. It should be:

appLabel.text = ((AppDelegate*)[UIApplication sharedApplication].delegate).appName;

But using such a property isn't necessary. You can get the app's display name without hardcoding it.

Get rid of your appName property and change this line of code to:

appLabel.text = [NSBundle mainBundle].infoDictionary[@"CFBundleDisplayName"];

This has the advantage of showing the right name even if you rename your app or localize it.

rmaddy
  • 314,917
  • 42
  • 532
  • 579