Instance方法从一个视图控制器返回正确的数组,但从其他控制器返回null

时间:2015-06-11 16:17:44

标签: objective-c xcode methods null instance

这是我的第一篇文章,对我所犯的任何错误表示歉意,但这让我感到很沮丧,因为我现在无法找到解决方案。

我有一个使用UITabBarViewController的应用程序,它有3个标签:FirstViewController,SecondViewController和ThirdViewController。

我有一个NSObject类(经理),我从我的视图控制器联系到从日历中提取信息。当我使用FirstViewController时,它工作得很好,但是,当我使用其他视图控制器时,它只返回“null”但我知道正在调用实例方法,因为我在实例方法中放了一个NSLog它返回一个值,但是这个值没有传递给视图控制器二和三。

我正在使用的代码如下。

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];

    }

这将返回null,但NSLog [NSLog(@“EKCalendars%@”,EKCalendars)]的输出提供的输出与为First View Controller运行代码时的输出完全相同。

我可以通过改变SecondViewController.m来读取日历来读取

    -(void)loadCalendars{


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

    }

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

感谢你们给予的任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用[UIApplication sharedApplication].delegate

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