是否有可能从AppDelegate获得NSArray?

时间:2016-07-14 07:08:06

标签: objective-c appdelegate

是否有可能从我的AppDelegate获得NSArray?我需要将数组发送到其他类。那个数组是在我的AppDelegate中生成的。谢谢!

3 个答案:

答案 0 :(得分:1)

首先,你应该allocinit 在AppDelegate.h文件中

@property(nonatomic,retain)NSArray *books; 

在AppDelegate.m文件中,您可以在其中添加对象。

_books = [[NSArray alloc]initWithObjects:@"test",@"test", nil];

你必须在BooksDetailViewController这样创建AppDelegate实例,

<。>文件中的

AppDelegate *appDelegate;

和.m文件

appDelegate  = (AppDelegate*)[UIApplication sharedApplication].delegate;

现在您可以像这样访问您的数组,

NSLog(@"Test Log :%@",appDelegate.books);

输出:

2016-07-14 13:04:08.211 Gridz[2490:39240] Test Log :(
test,
test
)

答案 1 :(得分:0)

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

现在您可以使用以下任何属性或方法:

[appDelegate myProperty][appDelegate myMethod]

希望这有帮助

答案 2 :(得分:0)

可以从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
)