我有几个 UIViewControllers 我试图访问我的 AppDelegate 中的一个数组。当我使用 IBAction UIButton 并在该方法中访问我的 AppDelegate 时,我的程序会默默地死掉。输出或调试器中没有任何内容,它只是停止。如果我多次运行它,我可以看到它无法正确访问数组。
为了调查这个问题,我创建了一个非常基本的应用程序。
在我的 AppDelegate.h 中,我声明并设置了数组的属性
#import <UIKit/UIKit.h>
@class MyViewController;
@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
MyViewController *viewController;
NSArray *images;
}
@property (nonatomic, retain) NSArray *images;
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet MyViewController *viewController;`
在 AppDelegate.m 中,我合成并初始化了 NSArray(同时确保将图像添加到 Resources 文件夹中)。
@synthesize images;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
images = [NSArray arrayWithObjects:
[[NSBundle mainBundle] pathForResource:@"bamboo_nw" ofType:@"jpg"],
.....
nil];
NSLog(@"init images size:%i",[images count]);
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
在我的 UIViewController.h 中,我为我的 AppDelegate 指针添加了类、导入的头文件、声明并设置了属性。
#import <UIKit/UIKit.h>
#import "MyAppDelegate.h"
@class MyAppDelegate;
@interface MyViewController : UIViewController {
MyAppDelegate *mainDelegate; IBOutlet UIButton mybutton; @property (nonatomic, 保留) MyAppDelegate mainDelegate; @property (nonatomic, 保留) UIButton *mybutton; -(IBAction)做某事;`
在我的 UIViewController.m 中,我合成并分配了我的 AppDelegate。我设置了一个 IBAction,它将记录来自 AppDelegate 的 NSArray 的相同计数。
#import "MyViewController.h"
#import "MyAppDelegate.h"
@implementation MyViewController
@synthesize mybutton;
- (void)viewDidLoad {
mainDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(@"vdl images size:%i",[mainDelegate.images count]);
[super viewDidLoad];
}
-(IBAction) doSomething {
NSLog(@"ds 图片大小:%i",[mainDelegate.images count]); }
当我创建它时,我在 AppDelegate 中打印 NSArray 的大小,当我第一次分配我的 AppDelegate 指针时在 ViewController 中打印它,然后作为我的 IBAction 的结果。
我发现每次我按下按钮时程序都会死掉。在我第三次按下按钮时,我看到它运行了我的 IBAction,但将我的数组大小打印为 1 而不是 8。我错过了什么吗?另外,为什么我没有得到堆栈跟踪或任何东西,调试器只是默默地死掉了?
提前感谢您的帮助!
3 次运行的调试器控制台输出:
[Session started at 2010-05-10 06:21:32 -0700.]
2010-05-10 06:21:44.865 My[59695:207] init images size:8
2010-05-10 06:21:47.246 My[59695:207] vdl images size:8
[Session started at 2010-05-10 06:22:15 -0700.]
2010-05-10 06:22:18.920 My[59704:207] init images size:8
2010-05-10 06:22:19.043 My[59704:207] vdl images size:8
[Session started at 2010-05-10 06:22:23 -0700.]
2010-05-10 06:22:25.966 My[59707:207] init images size:8
2010-05-10 06:22:26.017 My[59707:207] vdl images size:8
2010-05-10 06:22:27.814 My[59707:207] ds images size:1