实例方法 returns 从一个视图控制器正确数组但从其他视图控制器为 null

Instance method returns correct array from one view controller but null from others

这是我的第一个 post 对于我犯的任何错误,我深表歉意,但这让我沮丧了好几个小时,我找不到解决方案。

我有一个使用 UITabBarViewController 的应用程序,它有 3 个选项卡:FirstViewController、SecondViewController 和 ThirdViewController。

我有一个 NSObject class(管理器),我从我的视图控制器中伸出手来从日历中提取信息。当我使用 FirstViewController 时,它工作得很好,但是,当我去使用其他视图控制器时,它只是 returns "null" 但我知道正在调用实例方法,因为我在实例中放置了一个 NSLog方法它returns一个值,但是这个值没有被传递到视图控制器二和三。

我使用的代码如下。

AppDelegate.m

    #import <UIKit/UIKit.h>
    #import "EventManager.h"

    @interface AppDelegate : UIResponder <UIApplicationDelegate>{

    }

    @property (strong, nonatomic) UIWindow *window;
    @property (nonatomic, strong) EventManager *eventManager;

    @end

AppDelegate.m

    - (void)applicationDidBecomeActive:(UIApplication *)application {

        self.eventManager = [[EventManager alloc] init];

    }

EventManager.h

    #import <Foundation/Foundation.h>
    #import <EventKit/EKEventStore.h>

    @interface EventManager : NSObject

    @property (nonatomic, strong) EKEventStore *eventStore;

    -(NSMutableArray *) fetchCalendars;
    @end

EventManager.m

    -(NSMutableArray *) fetchCalendars {

        NSArray *EKCalendars = [self.eventStore         calendarsForEntityType:EKEntityTypeEvent];

        NSMutableArray *mutableCalendars = [[NSMutableArray alloc]         initWithArray:EKCalendars];
        NSLog(@"EKCalendars %@",EKCalendars);

        return mutableCalendars;
    }

FirstViewController.m

    -(void)loadCalendars{


            NSMutableArray *mutableCalendars = [self.appDelegate.eventManager fetchCalendars];

    }

加载日历绝对没问题。

SecondViewController.m

    -(void)loadCalendars{


            NSMutableArray *mutableCalendars = [self.appDelegate.eventManager fetchCalendars];

    }

This returns null,然而,NSLog[ NSLog(@"EKCalendars %@",EKCalendars)] 的输出给出了与代码为 运行 时完全相同的输出第一个视图控制器。

我可以通过更改 SecondViewController.m 来获取日历

    -(void)loadCalendars{


    EventManager *per= [[EventManager alloc]init];
    calendarsArray =   [per fetchCalendars];

    }

但我只是不明白为什么我需要重新初始化事件管理器,因为它是在 applicationDidBecomeActive 中初始化的。

感谢您提供的任何帮助。

您可以使用 [UIApplication sharedApplication].delegate:

访问应用程序的 AppDelegate
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSMutableArray *mutableCalendars = [appDelegate.eventManager fetchCalendars];