可以从 AppDelegate 获取 NSArray 到其他类。
AppDelegate.h
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate> {
}
@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) ViewController *viewController; //For Xib
@property (nonatomic, strong) NSArray *arrayObjects;
@end
AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
@implementation AppDelegate
@synthesize arrayObjects;
由于我使用的是Xib,所以我在下面的方法中设置了根视图控制器。如果你使用stroy board,只添加NSArray对象就足够了。不需要设置根视图控制器。
//For XIB
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
arrayObjects = [[NSArray alloc]initWithObjects:@"Steve",@"jobs",@"Tim",@"Cook",nil];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
self.window.rootViewController = navController;
[navController setNavigationBarHidden:YES];
[self.window makeKeyAndVisible];
return YES;
}
//For Storyboard
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
arrayObjects = [[NSArray alloc]initWithObjects:@"Steve",@"jobs",@"Tim",@"Cook",nil];
return YES;
}
然后在 ViewController.m 中
也可以在 ViewController.m 中导入 AppDelegate
#import "ViewController.h"
#import "AppDelegate.h"
@interface ViewController ()
@end
@implementation ViewController
现在在 viewDidLoad 方法中
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSLog(@"The app delegate NSArray Objects are - %@",delegate.arrayObjects);
}
NSLog 结果是
The app delegate NSArray Objects are - (
Steve,
jobs,
Tim,
Cook
)